bzoj1602 [Usaco2008 Oct]牧场行走
2014-05-31 22:51
363 查看
Description
N头牛(2<=n<=1000)别人被标记为1到n,在同样被标记1到n的n块土地上吃草,第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走,第i条边连接第Ai,Bi块牧场,第i条边的长度是Li(1<=Li<=10000)。 这些边被安排成任意两头奶牛都可以通过这些边到达的情况,所以说这是一棵树。 这些奶牛是非常喜欢交际的,经常会去互相访问,他们想让你去帮助他们计算Q(1<=q<=1000)对奶牛之间的距离。Input
*第一行:两个被空格隔开的整数:N和Q*第二行到第n行:第i+1行有两个被空格隔开的整数:AI,BI,LI
*第n+1行到n+Q行:每一行有两个空格隔开的整数:P1,P2,表示两头奶牛的编号。
Output
*第1行到第Q行:每行输出一个数,表示那两头奶牛之间的距离。Sample Input
4 22 1 2
4 3 2
1 4 3
1 2
3 2
Sample Output
27
很简单的lca。但我闲着无聊打了个bfs……反正时限多
#include<cstdio> #include<iostream> #include<cstring> using namespace std; struct aaa{ int to,next,v; }e[5000000]; int n,m,cnt,x,y,z; int head[100000]; int map[1001][1001]; bool mark[100000]; void ins(int u,int v,int w) { e[++cnt].to=v; e[cnt].v=w; e[cnt].next=head[u]; head[u]=cnt; } void insert(int u,int v,int w) { ins(u,v,w); ins(v,u,w); } int bfs(int from) { int queue[10000]; int dist[10000]; int t=0,w=1; bool mark[10000]; memset(queue,0,sizeof(queue)); memset(mark,0,sizeof(mark)); memset(dist,0,sizeof(dist)); queue[1]=from; mark[from]=1; while (t<w) { t++; int i=head[queue[t]]; while (i) { if (!mark[e[i].to]) { queue[++w]=e[i].to; dist[e[i].to]=dist[queue[t]]+e[i].v; mark[e[i].to]=1; if (e[i].to==y) return dist[y]; } i=e[i].next; } } return dist[y]; } int main() { scanf("%d%d",&n,&m); for (int i=1;i<=n-1;i++) { cin>>x>>y>>z; insert(x,y,z); } for (int i=1;i<=m;i++) { cin>>x>>y; memset(mark,0,sizeof(mark)); cout<<bfs(x)<<endl; } }
相关文章推荐
- bzoj 1602: [Usaco2008 Oct]牧场行走【瞎搞】
- bzoj 1602 [Usaco2008 Oct]牧场行走(LCA模板)
- bzoj1602[Usaco2008 Oct]牧场行走(lca模版)
- bzoj 1602: [Usaco2008 Oct]牧场行走
- [Usaco2008 Oct][BZOJ1602] 牧场行走
- BZOJ1602: [Usaco2008 Oct]牧场行走
- [BZOJ1602][Usaco2008 Oct]牧场行走
- BZOJ 1602: [Usaco2008 Oct]牧场行走
- bzoj1602 [Usaco2008 Oct]牧场行走
- BZOJ 1602 Usaco2008 Oct 牧场行走 倍增LCA
- 【BZOJ】1602:[Usaco2008 Oct]牧场行走
- 【bzoj1602】【Usaco2008 Oct】牧场行走 (暴力) 题解&代码
- 【bzoj 1602】[Usaco2008 Oct]牧场行走
- 【bzoj1602】[Usaco2008 Oct]牧场行走
- BZOJ 1602 USACO2008 Oct 牧场行走
- bzoj1602: [Usaco2008 Oct]牧场行走 暴力dfs
- bzoj1602 [Usaco2008 Oct]牧场行走
- bzoj 1602 [Usaco2008 Oct]牧场行走(LCA模板)
- BZOJ 1602 [Usaco2008 Oct]牧场行走 dfs
- 【BZOJ】1602: [Usaco2008 Oct]牧场行走(lca)