问题描述
One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.
Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.
Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?
输入
Line 1: Three space-separated integers, respectively: N, M, and X
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.
输出
Line 1: One integer: the maximum of time any one cow must walk.
样例输入
4 8 2 1 2 4 1 3 2 1 4 7 2 1 1 2 3 5 3 1 2 3 4 4 4 2 3
样例输出
10
提示
Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.
//求所有最小路径中的最大值
//从起点到终点,从终点到起点的和的最小路径
//从起点到终点,从终点到起点的和的最小路径
从终点到起点计算时,建立另外一个反向图,把终点设为起点
注意vis 在算第二个最短路径时要重新初始化!
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5 const int N=1100; 6 const int inf=1<<29; 7 int u,v,m,n,q,c; 8 int d1[N],d2[N],w1[N][N],w2[N][N],vis[N]; 9 void dij1(int st) 10 { 11 for(int i=1;i<=n;i++) 12 { 13 d1[i]=inf; 14 } 15 d1[st]=0; 16 for(int i=1;i<=n;i++) 17 { 18 int now=inf; 19 int x; 20 for(int j=1;j<=n;j++) 21 { 22 if(!vis[j]&&now>d1[j]) 23 { 24 now=d1[j]; 25 x=j; 26 } 27 } 28 vis[x]=1; 29 for(int j=1;j<=n;j++) 30 { 31 if(!vis[j]&&d1[j]>d1[x]+w1[x][j]) 32 { 33 d1[j]=d1[x]+w1[x][j]; 34 } 35 } 36 } 37 } 38 void dij2(int st) 39 { 40 memset(vis,0,sizeof(vis)); 41 for(int i=1;i<=n;i++) 42 { 43 d2[i]=inf; 44 } 45 d2[st]=0; 46 for(int i=1;i<=n;i++) 47 { 48 int now=inf; 49 int x; 50 for(int j=1;j<=n;j++) 51 { 52 if(!vis[j]&&now>d2[j]) 53 { 54 now=d2[j]; 55 x=j; 56 } 57 } 58 vis[x]=1; 59 for(int j=1;j<=n;j++) 60 { 61 if(!vis[j]&&d2[j]>d2[x]+w2[x][j]) 62 { 63 d2[j]=d2[x]+w2[x][j]; 64 } 65 } 66 } 67 } 68 int main() 69 { 70 while(scanf("%d%d%d",&n,&m,&q)!=EOF) 71 { 72 memset(vis,0,sizeof(vis)); 73 for(int i=1; i<=n; i++) 74 { 75 for(int j=1; j<=n; j++) 76 { 77 w1[i][j]=inf; 78 w2[i][j]=inf; 79 } 80 } 81 for(int i=1; i<=m; i++) 82 { 83 scanf("%d%d%d",&u,&v,&c); 84 if(c<w1[u][v]&&c<w2[v][u]) 85 { 86 w1[u][v]=c; 87 w2[v][u]=c; 88 } 89 } 90 dij1(q); 91 dij2(q); 92 int maxn=-inf; 93 for(int i=2;i<=n;i++) 94 { 95 if(maxn<d1[i]+d2[i]) 96 maxn=d1[i]+d2[i]; 97 } 98 printf("%d ",maxn); 99 } 100 return 0; 101 }