题目链接 : https://cn.vjudge.net/contest/290751#problem/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.
题目大意: 有n-1个牛要去一个x的地方参加聚会,而且参加完聚会还要回到原来的地方,让我们求所有的牛通过最近路到达目的地,所走的路的最长的牛的路程。
思路:
用两次迪杰斯特拉,分别求每个牛到x的最短路和每个牛从x到它原来的地方的最短路之和,用一个数组存着,最后比较最大即可。注意第一次和第二次迪杰斯特拉的代码有点不同,因为两次的方向不一样,
所以第一次是
d[j]=min(d[j],d[u]+e[u][j]);
第二次是
v[j]=min(v[j],v[u]+e[j][u]);
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int e[1005][1005];
int d[1005];
int v[1005];
int w[1005];
int q[1005];
int sum[1005];
int main()
{
int n,m,x;
scanf("%d%d%d",&n,&m,&x);
memset(e,0x3f3f3f,sizeof(e));
for(int i=1; i<=m; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
e[a][b]=c;
}
for(int i=1;i<=n;i++)
{
e[i][i]=0;
d[i]=e[x][i];
v[i]=e[i][x];
}
w[x]=1;
q[x]=1;
for(int i=1;i<=n;i++)
{
int mx=0x3f3f3f;
int u=-1;
for(int k=1;k<=n;k++)
{
if(w[k]==0&&d[k]<mx)
{
mx=d[k];
u=k;
}
}
w[u]=1;
for(int j=1;j<=n;j++)
{
if(w[j]==0&&d[j]>(d[u]+e[u][j]))
{
d[j]=min(d[j],d[u]+e[u][j]);
}
}
}
// for(int i=1;i<=n;i++)
// {
// for(int j=i;j<=n;j++)
// {
// int tem;
// tem=e[j][i];
// e[j][i]=e[i][j];
// e[i][j]=tem;
//
// }
// }
for(int i=1;i<=n;i++)
{
int mx=0x3f3f3f;
int u=-1;
for(int k=1;k<=n;k++)
{
if(q[k]==0&&v[k]<mx)
{
mx=v[k];
u=k;
}
}
q[u]=1;
for(int j=1;j<=n;j++)
{
if(q[j]==0&&v[j]>(v[u]+e[j][u]))
{
v[j]=min(v[j],v[u]+e[j][u]);
}
}
}
for(int i=1;i<=n;i++)//路走不通就不要加进去,最后比较时会淘汰这种方式。
{
if(d[i]<0x3f3f3f)
{
sum[i]+=d[i];
}
if(v[i]<0x3f3f3f)
{
sum[i]+=v[i];
}
}
int mm=-1;
for(int i=1;i<=n;i++)
{
if(i!=x)
mm=max(mm,sum[i]);
}
printf("%d\n",mm);
return 0;
}