POJ:3268
Silver Cow Party
Time Limit: 2000MS
Memory Limit: 65536K
Description
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
题目大意就是求单点到其他点的最短路与其他路回单点的和的最大值。一开始用floyd就直接超时,然后也没多想,对每个点用一遍dijkstra,过是过了,但是总感觉有更简单的方法,后面学到了这个转置的方法,只要用两遍dijkstra。第一次用自然可以求出单点到其他路的最短路,然后我们只要将我们的储存边的邻接矩阵转置,这里假设邻接矩阵是G[ ][ ],那么我们只要把G[i][j]=G[j][i],然后再做一遍dijkstra,求出的就是其他路返回的最短路。为什么呢,因为转置之后,就相当于把所有路反向了,那么再求dijkstra可以理解为还是单点x到其他路的最短路,但是所有的路和原来相比都是反的,那么现在求的x到其他路的最短路就是原来其他路到x的最短路了。把两个最短路相加求最大就可以求出答案了。
#include<iostream>
#include<cstdio>
#define INF 999999999
using namespace std;
int G[1005][1005],d[1005],vis[1005],sum[1005];
int n,m,x;
void dij(int s)
{
fill(d+1,d+1+n,INF);
fill(vis+1,vis+1+n,0);
d[s]=0;
while(true)
{
int v=-1;
for(int u=1;u<=n;++u)
if(!vis[u]&&(v==-1||d[u]<d[v])) v=u;
if(v==-1)
break;
vis[v]=1;
for(int u=1;u<=n;++u)
d[u]=min(d[u],d[v]+G[v][u]);
}
for(int i=1;i<=n;++i)
sum[i]+=d[i];
}
int main()
{
cin>>n>>m>>x;
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
if(i==j)
G[i][j]=0;
else
G[i][j]=INF;
}
}
int a,b,c;
for(int i=0;i<m;++i)
{
cin>>a>>b>>c;
G[a][b]=c;
}
dij(x);
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
swap(G[i][j],G[j][i]);
dij(x);
int ans=-1;
for(int i=1;i<=n;++i)
ans=max(ans,sum[i]);
cout<<ans;
}