基础最短路(模板 spfa)

Description

虽然草儿是个路痴(就是在杭电待了一年多,居然还会在校园里迷路的人,汗~),但是草儿仍然很喜欢旅行,因为在旅途中 会遇见很多人(白马王子,^0^),很多事,还能丰富自己的阅历,还可以看美丽的风景……草儿想去很多地方,她想要去东京铁塔看夜景,去威尼斯看电影,去 阳明山上看海芋,去纽约纯粹看雪景,去巴黎喝咖啡写信,去北京探望孟姜女……眼看寒假就快到了,这么一大段时间,可不能浪费啊,一定要给自己好好的放个 假,可是也不能荒废了训练啊,所以草儿决定在要在最短的时间去一个自己想去的地方!因为草儿的家在一个小镇上,没有火车经过,所以她只能去邻近的城市坐火 车(好可怜啊~)。
 

Input

输入数据有多组,每组的第一行是三个整数T,S和D,表示有T条路,和草儿家相邻的城市的有S个,草儿想去的地方有D个;
接着有T行,每行有三个整数a,b,time,表示a,b城市之间的车程是time小时;(1=<(a,b)<=1000;a,b 之间可能有多条路)
接着的第T+1行有S个数,表示和草儿家相连的城市;
接着的第T+2行有D个数,表示草儿想去地方。
 

Output

输出草儿能去某个喜欢的城市的最短时间。
 

Sample Input

6 2 3
1 3 5
1 4 7
2 8 12
3 8 4
4 9 12
9 10 2
1 2
8 9 1
 

Sample Output

9
 
题目解析:最短路,模板题。单源最短路多次,找次最小的。
 
代码如下:
 1 # include<iostream>
 2 # include<cstdio>
 3 # include<cstring>
 4 # include<queue>
 5 # include<algorithm>
 6 using namespace std;
 7 const int INF=1<<30;
 8 struct edge
 9 {
10     int to,w,nxt;
11 };
12 edge e[2005];
13 int head[1005],dis[1005];
14 int t,s,d,cnt,sta[1005],ed[1005];
15 void add(int a,int b,int c)
16 {
17     e[cnt].to=b;
18     e[cnt].w=c;
19     e[cnt].nxt=head[a];
20     head[a]=cnt++;
21 }
22 int spfa(int from,int to)
23 {
24     fill(dis,dis+1004,INF);
25     dis[from]=0;
26     queue<int>q;
27     q.push(from);
28     while(!q.empty()){
29         int u=q.front();
30         q.pop();
31         for(int i=head[u];i!=-1;i=e[i].nxt){
32             if(dis[e[i].to]>dis[u]+e[i].w){
33                 dis[e[i].to]=dis[u]+e[i].w;
34                 q.push(e[i].to);
35             }
36         }
37     }
38     return dis[to];
39 }
40 int main()
41 {
42     int i,j,a,b,c;
43     while(scanf("%d%d%d",&t,&s,&d)!=EOF)
44     {
45         cnt=0;
46         memset(head,-1,sizeof(head));
47         for(i=1;i<=t;++i){
48             scanf("%d%d%d",&a,&b,&c);
49             add(a,b,c);
50             add(b,a,c);
51         }
52         for(i=0;i<s;++i)
53             scanf("%d",&sta[i]);
54         for(i=0;i<d;++i)
55             scanf("%d",&ed[i]);
56         int ans=INF;
57         for(i=0;i<s;++i)
58             for(j=0;j<d;++j)
59                 ans=min(ans,spfa(sta[i],ed[j]));
60         printf("%d
",ans);
61     }
62     return 0;
63 }
View Code
原文地址:https://www.cnblogs.com/20143605--pcx/p/4677202.html