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.

  1/* ***********************************************
  2Author :111qqz
  3Created Time :2016年03月31日 星期四 20时27分01秒
  4File Name :code/bzoj/1602.cpp
  5************************************************ */
  6
  7#include <cstdio>
  8#include <cstring>
  9#include <iostream>
 10#include <algorithm>
 11#include <vector>
 12#include <queue>
 13#include <set>
 14#include <map>
 15#include <string>
 16#include <cmath>
 17#include <cstdlib>
 18#include <ctime>
 19#define fst first
 20#define sec second
 21#define lson l,m,rt<<1
 22#define rson m+1,r,rt<<1|1
 23#define ms(a,x) memset(a,x,sizeof(a))
 24typedef long long LL;
 25#define pi pair < int ,int >
 26#define MP make_pair
 27
 28using namespace std;
 29const double eps = 1E-8;
 30const int dx4[4]={1,0,0,-1};
 31const int dy4[4]={0,-1,1,0};
 32const int inf = 0x3f3f3f3f;
 33const int N=1E3+5;
 34int n,q;
 35vector< pi >edge[N];
 36bool vis[N];
 37int d[N];
 38
 39struct node
 40{
 41    int x;
 42    int d;
 43
 44    bool operator < (node b)const
 45    {
 46	return d>b.d;
 47    }
 48};
 49
 50int bfs( int s,int t)
 51{
 52    priority_queue<node>q;
 53    ms(vis,false);
 54    node tmp;
 55    tmp.x = s;
 56    tmp.d = 0 ;
 57    q.push(tmp);
 58    vis[s] = true;
 59    while (!q.empty())
 60    {
 61	node pre = q.top();q.pop();
 62	if (pre.x==t) return pre.d;
 63	for ( int i = 0 ; i < int(edge[pre.x].size()) ; i++)
 64	{
 65	    node nxt;
 66	    nxt.x= edge[pre.x][i].fst;
 67	    nxt.d = pre.d + edge[pre.x][i].sec;
 68	    if (!vis[nxt.x])
 69	    {
 70
 71		q.push(nxt);
 72		vis[nxt.x] = true;
 73	    }
 74	}
 75    }
 76    return -1;
 77
 78}
 79int main()
 80{
 81	#ifndef  ONLINE_JUDGE 
 82	freopen("code/in.txt","r",stdin);
 83  #endif
 84
 85	ios::sync_with_stdio(false);
 86	cin>>n>>q;
 87	for ( int i = 1 ; i <= n-1 ; i++)
 88	{
 89	    int u,v,w;
 90	    cin>>u>>v>>w;
 91	    edge[u].push_back(make_pair(v,w));
 92	    edge[v].push_back(make_pair(u,w));
 93	}
 94
 95	while (q--)
 96	{
 97	    int s,t;
 98	    cin>>s>>t;
 99	    int ans = bfs(s,t);
100	    cout<<ans<<endl;
101	}
102
103
104  #ifndef ONLINE_JUDGE  
105  fclose(stdin);
106  #endif
107    return 0;
108}