bzoj 1602: [Usaco2008 Oct]牧场行走 (bfs,优先队列)
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 2
2 1 2
4 3 2
1 4 3
1 2
3 2
Sample Output
2
7
思路:直接bfs....貌似因为每个点最多只和两个边相连。。。不用优先队列也行? 1A,好爽23333.
/* ***********************************************
Author :111qqz
Created Time :2016年03月31日 星期四 20时27分01秒
File Name :code/bzoj/1602.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E3+5;
7int n,q;
8vector< pi >edge[N];
9bool vis[N];
10int d[N];
1struct node
2{
3 int x;
4 int d;
1 bool operator < (node b)const
2 {
3 return d>b.d;
4 }
5};
1int bfs( int s,int t)
2{
3 priority_queue<node>q;
4 ms(vis,false);
5 node tmp;
6 tmp.x = s;
7 tmp.d = 0 ;
8 q.push(tmp);
9 vis[s] = true;
10 while (!q.empty())
11 {
12 node pre = q.top();q.pop();
13 if (pre.x==t) return pre.d;
14 for ( int i = 0 ; i < int(edge[pre.x].size()) ; i++)
15 {
16 node nxt;
17 nxt.x= edge[pre.x][i].fst;
18 nxt.d = pre.d + edge[pre.x][i].sec;
19 if (!vis[nxt.x])
20 {
1 q.push(nxt);
2 vis[nxt.x] = true;
3 }
4 }
5 }
6 return -1;
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
1 ios::sync_with_stdio(false);
2 cin>>n>>q;
3 for ( int i = 1 ; i <= n-1 ; i++)
4 {
5 int u,v,w;
6 cin>>u>>v>>w;
7 edge[u].push_back(make_pair(v,w));
8 edge[v].push_back(make_pair(u,w));
9 }
1 while (q--)
2 {
3 int s,t;
4 cin>>s>>t;
5 int ans = bfs(s,t);
6 cout<<ans<<endl;
7 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}