POJ-3268-D

题目描述:
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
Hint
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.


思路:分别求每个点去x和从x走到每个点的最短路,最后分别求和取最大值即可。用到了两次dijk算法。多点到一点的最短路,就是把距离矩阵转置(所有路换方向),然后就变成了单点到多点的最短路。

坑点:max()和min()函数是<algorithm>里的。


 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define Inf 0x3f3f3f3f
 5 using namespace std;
 6 int G[1005][1005],mark[1005],dis1[1005],dis2[1005];
 7 int m,n,x;
 8 
 9 void Getmap(){
10     int u,v,w;
11     memset(G,Inf,sizeof(G));
12     for(int i=1;i<=n;i++)
13         G[i][i]=0;
14     for(int i=0;i<m;i++){
15         scanf("%d%d%d",&u,&v,&w);
16         G[u][v]=w;
17     }    
18 }
19 
20 void Dijk(){
21     int mini,p;
22     memset(mark,0,sizeof(mark));
23     for(int i=1;i<=n;i++){
24         dis1[i]=G[i][x];//来x 
25         dis2[i]=G[x][i];//从x回去;    
26     }
27     
28     for(int k=0;k<n;k++){
29         mini=Inf;
30         for(int i=1;i<=n;i++)
31             if(!mark[i]&&dis1[i]<mini){
32                 mini=dis1[i];
33                 p=i;
34             }
35         
36         mark[p]=1;
37         for(int i=1;i<=n;i++)
38            dis1[i]=min(dis1[i],dis1[p]+G[i][p]);    
39     }
40     
41     memset(mark,0,sizeof(mark));
42     for(int k=0;k<n;k++){
43         mini=Inf;
44         for(int i=1;i<=n;i++)
45             if(!mark[i]&&dis2[i]<mini){
46                 mini=dis2[i];
47                 p=i;
48             }
49         
50         mark[p]=1;
51         for(int i=1;i<=n;i++)
52             dis2[i]=min(dis2[i],dis2[p]+G[p][i]);         
53     }     
54 } 
55 
56 int main(){
57     scanf("%d%d%d",&n,&m,&x);
58     Getmap();
59     Dijk();
60     int ans=0;
61     for(int i=1;i<=n;i++) 
62        ans=max(ans,dis1[i]+dis2[i]);
63     printf("%d
",ans);   
64     return 0;
65 } 
原文地址:https://www.cnblogs.com/yzhhh/p/9978443.html