POJ3268-Silver Cow Party(最短路径)

来源:互联网 发布:java批量导入数据 编辑:程序博客网 时间:2024/05/21 07:55

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 ≤XN). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; roadi 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 farmAi 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 21 2 41 3 21 4 72 1 12 3 53 1 23 4 44 2 3

Sample Output

10


题目大概的意思是:有一群牛,其中有一头牛(x)想要派对,然后其他的牛也要过来庆祝。

问其他牛去那里参加派对并且回去所花费的最短时间。然后从这些牛中的最短时间里选择

一个最大时间回去的牛。这是一个有向图。

思路:所有牛到牛(x)的最短路径,只要从牛(x)这里用DIJ走一遍就可以求出所有牛到其的

最短路径。然后求所有牛回去的最短路径。只要把所有的边的方向变换一下,就相当于在求一边

所有牛到牛(x)的最短的距离,求的时候只要开两个数组保存两次所求的最短路。从而找出最大值即可。

#include<stdio.h>#include<string.h>#include<iostream>using namespace std;const int maxn=1001;const int inf=1<<29;int vis[maxn],d1[maxn],d2[maxn],w[maxn][maxn];int n,m,x;int cnt=0;void DIJ(int *d){    for(int i=1;i<=n;i++)        d[i]=inf;    d[x]=0;    memset(vis,0,sizeof(vis));    for(int i=0;i<n;i++)    {        int now=inf;        int u;        for(int j=1;j<=n;j++)        {            if(!vis[j]&&now>d[j])            {                now=d[j];                u=j;            }        }        vis[u]=1;        for(int j=1;j<=n;j++)            if(d[j]>d[u]+w[u][j])                d[j]=d[u]+w[u][j];    }}void zhuanhuan(){    for(int i=1;i<=n;i++)        for(int j=i+1;j<=n;j++)            swap(w[i][j],w[j][i]);}int main(){    scanf("%d%d%d",&n,&m,&x);    {        for(int i=1;i<=n;i++)            for(int j=1;j<=n;j++)                w[i][j]=inf;        for(int i=0;i<m;i++)        {            int u,v,c;            scanf("%d%d%d",&u,&v,&c);            w[u][v]=c;        }        DIJ(d1);        zhuanhuan();        DIJ(d2);        int ans=0;        for(int i=1;i<=n;i++)            ans=max(ans,d1[i]+d2[i]);        printf("%d\n",ans);    }    return 0;}


0 0