2015: [Usaco2010 Feb]Chocolate Giving

Description

Farmer John有B头奶牛(1<=B<=25000),有N(2*B<=N<=50000)个农场,编号1-N,有M(N-1<=M<=100000)条双向边,第i条边连接农场R_i和S_i(1<=R_i<=N;1<=S_i<=N),该边的长度是L_i(1<=L_i<=2000)。居住在农场P_i的奶牛A(1<=P_i<=N),它想送一份新年礼物给居住在农场Q_i(1<=Q_i<=N)的奶牛B,但是奶牛A必须先到FJ(居住在编号1的农场)那里取礼物,然后再送给奶牛B。你的任务是:奶牛A至少需要走多远的路程?

 

 

Input

  第1行:三个整数:N,M,B。

    第2..M+1行:每行三个整数:R_i,S_i和L_i,描述一条边的信息。

  第M+2..M+B+1行:共B行,每行两个整数P_i和Q_i,表示住在P_i农场的奶牛送礼物给住在Q_i农场的奶牛。

  

Output

 

  样例输出:

  共B行,每行一个整数,表示住在P_i农场的奶牛送礼给住在Q_i农场的奶牛至少需要走的路程

 

Sample Input

6 7 3

  1 2 3

  5 4 3

  3 1 1

  6 1 9

  3 4 2

  1 4 4

  3 2 2

  2 4

  5 1

  3 6


Sample Output

 6

 6

10
 
SPFA....
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<queue>
 7 #include<set>
 8 #include<map>
 9 #include<vector>
10 #define maxn 50010
11 #define maxm 100010
12 #define inf 100000000
13 #define ll long long
14 using namespace std;
15 struct edge{int go,next,w;}e[2*maxm];
16 int n,m,k,t,tot,q[maxn],d[maxn],head[maxn],b;
17 bool v[maxn];
18 void ins(int x,int y,int z)
19 {
20     e[++tot].go=y;e[tot].w=z;e[tot].next=head[x];head[x]=tot;
21 }
22 void insert(int x,int y,int z)
23 {
24     ins(x,y,z);ins(y,x,z);
25 }
26 void spfa(int s)
27 {
28     for(int i=1;i<=n;++i) d[i]=inf;
29     memset(v,0,sizeof(v));
30     int l=0,r=1,x,y;q[1]=s;d[s]=0;
31     while(l!=r)
32     {
33         x=q[++l];if(l==maxn)l=0;v[x]=0;
34         for(int i=head[x];i;i=e[i].next)
35          if(d[x]+e[i].w<d[y=e[i].go])
36          {
37             d[y]=d[x]+e[i].w;
38             if(!v[y]){v[y]=1;q[++r]=y;if(r==maxn)r=0;}
39          }
40     }
41 }
42 int main(){
43     scanf("%d%d%d",&n,&m,&b);
44     for(int i=1,x,y,z;i<=m;i++){
45         scanf("%d%d%d",&x,&y,&z);
46         insert(x,y,z);
47     }
48     spfa(1);
49     for(int i=1,x,y;i<=b;i++){
50         scanf("%d%d",&x,&y);
51         printf("%d\n",d[x]+d[y]);
52     }
53     return 0;
54 }
View Code

 

posted @ 2015-10-23 08:25  HTWX  阅读(121)  评论(0编辑  收藏  举报