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?
Input 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. Output Line 1: One integer: the maximum of time any one cow must walk. Sample Input 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 Sample Output 10 HintCow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.
这道题最重要的一个地方就是求多个点到一个点的距离,这里有一个很巧妙的方法,就是将邻接矩阵逆转,很皮,没毛病。
#include<iostream> #include<stdlib.h> #include<string.h> #include<stdio.h> #include<queue> #define INF 99999999 using namespace std; int N,M,X; int map1[1001][1001]; int map2[1001][1001]; int vis[1001]; int pre[1001]; void SPFA(int s); /*void Flody() { int i,j,k; for(k=1;k<=N;k++) for(i=1;i<=N;i++) for(j=1;j<=N;j++) if(map1[i][j]>map1[i][k]+map1[k][j]) map1[i][j]=map1[i][k]+map1[k][j]; }*/ int main() { int i,j,tx,ty,tt; scanf("%d %d %d",&N,&M,&X); for(i=1;i<=N;i++) for(j=1;j<=N;j++) { if(i==j) { map1[i][j]=map2[i][j]=0; } else map1[i][j]=map2[i][j]=INF; } for(i=1;i<=M;i++) { scanf("%d %d %d",&tx,&ty,&tt); map1[tx][ty]=map2[tx][ty]=tt; } //Flody(); SPFA(X); int dis[1001]; for(i=1;i<=N;i++) dis[i]=pre[i]; int temp; for(i = 1; i <= N; i++){ for(j = 1; j <= i; j++){ swap(map2[i][j], map2[j][i]); } } SPFA(X); int max=0; for(i=1;i<=N;i++) { if(dis[i]+pre[i]>max) max=dis[i]+pre[i]; } cout<<max<<endl; return 0; } void SPFA(int s) { int q,i,j; queue<int> Q; while(!Q.empty()) Q.pop(); memset(vis,0,sizeof(vis)); memset(pre,0x3F,sizeof(pre)); pre[s]=0; vis[s]=1; Q.push(s); while(!Q.empty()) { q=Q.front(); Q.pop(); for(i=1;i<=N;i++) { if(pre[q]+map2[q][i] < pre[i]) { pre[i]=pre[q]+map2[q][i]; if(vis[i]==0) { Q.push(i); vis[i]=1; } } } vis[q]=0; } }