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
题意
N个农场各一头奶牛(1≤ N≤ 1000)方便编号的1…N将参加在X农场举行的大型奶牛派对(1≤ X≤ N) 。共M(1≤ M≤ 100000)单向道路连接两个农场;
每头牛必须步行去参加聚会,聚会结束后,再回到她的农场。每头牛都是懒惰的,因此选择最短时间的最佳路线。牛的返回路线可能与她最初去聚会的路线不同,因为道路是单向的。
在所有奶牛中,奶牛步行到聚会和回来的时间最长是多少?
代码
#include "stdio.h"
#include "string.h"
#include "algorithm"
using namespace std;
#define inf 0X3f3f3f
int b[100009],a[100009],c[100009],d1[100009],d2[100009],d[100009];
//d1数组记录牛从k(聚会的农场)到n(1,2,3,……)时间,起点固定
//d2数组记录牛从n(1,2,3,……)到k(聚会农场)时间,终点固定
int main()
{
int i,j,n,m,k,l;
scanf("%d %d %d",&n,&m,&k);
memset(d1,inf,sizeof(d1));
memset(d2,inf,sizeof(d2));
for(j=1;j<=m;j++)
scanf("%d %d %d",&a[j],&b[j],&c[j]);
d1[k]=0;
d2[k]=0;
for(l=1;l<n;l++)
{
for(j=1;j<=m;j++)
{
if(d1[a[j]]>c[j]+d1[b[j]])//判断从a[j]到k(聚会农场)是否经过b[j]这个转折点更快
d1[a[j]]=c[j]+d1[b[j]];
if(d2[b[j]]>d2[a[j]]+c[j])//判断从k(聚会农场)到b[j]是否经过a[j]这个转折点更快
d2[b[j]]=d2[a[j]]+c[j];
}
}
for(i=1;i<=n;i++)
d[i]=d1[i]+d2[i];
sort(d+1,d+n+1);
printf("%d\n",d[n]);
}