Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 16998 | Accepted: 7757 |
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
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
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
Source
题意:有n头牛去一头牛x家开会,给了m条有向边,每一条边都有对应的时间值,一头牛来了之后还是要回去的,所以会生成一个时间值,求这个时间值的最大。
解题思路:x到每一头牛最短的时间很容易求出来,迪杰斯特拉就好,但是每一头牛去的时间不好求,我们可以想象一下去的图还有回来的图,去的图像是一群指向x的有向边,回来的图是一群由x发出的边,既然我们可以求出x发出的直线,那我们只需要将射向x的边反向就行,然后再来一次迪杰斯特拉,有了两个时间数组就什么都有了
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
#define MAXN 1010
#define INF 0x3f3f3f
int n,m,x;
int d[1010],dback[1010],vis[1010],map[1010][1010];
int disj()
{
memset(vis,0,sizeof(vis));
memset(d,INF,sizeof(d));
memset(dback,INF,sizeof(dback));
for(int i=1;i<=n;i++)
{
d[i]=map[x][i];
dback[i]=map[i][x];
}
for(int i=1;i<n;i++)
{
int minn=INF;
int flag=-1;
for(int j=1;j<=n;j++)
{
if(minn>d[j]&&!vis[j])
{
minn=d[j];
flag=j;
}
}
vis[flag]=1;
for(int j=1;j<=n;j++)
if(d[j]>d[flag]+map[flag][j])
d[j]=d[flag]+map[flag][j];
}
memset(vis,0,sizeof(vis));
for(int i=1;i<n;i++)
{
int minn=INF;
int flag=-1;
for(int j=1;j<=n;j++)
{
if(minn>dback[j]&&!vis[j])
{
minn=dback[j];
flag=j;
}
}
vis[flag]=1;
for(int j=1;j<=n;j++)
if(dback[j]>dback[flag]+map[j][flag])
dback[j]=dback[flag]+map[j][flag];
}
int maxx=-1;
for(int i=1;i<=n;i++)
// if(i!=x)
maxx=max(d[i]+dback[i],maxx);
return maxx;
}
int main()
{
while(scanf("%d%d%d",&n,&m,&x)!=EOF)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(i==j) continue;
map[i][j]=map[j][i]=INF;
}
int a,b,c;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
if(c<map[a][b])
map[a][b]=c;
}
printf("%d\n",disj());
}
return 0;
}