题目:
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,M,X,代表有N个地点,M条路径,要到X参加聚会;
下面是M组路径 a,b,c,代表从a到b之间有一条长度为c的路径;
思路:
双层Dijkstra,对于图进行最短路算法,记录下来来回的距离和,数字出最大值;
代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define INF 500000
using namespace std;
int sum[1010];
int map[1010][1010];
int dis[1010],diss[1010],mark[1010];
int x,n,i,j;
void Dijkstra()
{
int min,k;
memset(dis,0,sizeof(dis));
memset(mark,0,sizeof(mark));
for(i=1; i<=n; i++)
{
dis[i]=map[x][i];
}
dis[x]=0;
mark[x]=1;
for(i=2; i<=n; i++)
{
min=INF;
for(j=1; j<=n; j++)
{
if(mark[j]==0&&min>dis[j])
{
k=j;
min=dis[j];
}
}
mark[k]=1;
for(j=1; j<=n; j++)
{
if(!mark[j]&&map[k][j]+dis[k]<dis[j])
{
dis[j]=map[k][j]+dis[k];
}
}
}
}
void Dijkstraa()
{
int min,k;
memset(diss,0,sizeof(diss));
memset(mark,0,sizeof(mark));
for(i=1; i<=n; i++)
{
diss[i]=map[x][i];
}
diss[x]=0;
mark[x]=1;
for(i=2; i<=n; i++)
{
min=INF;
for(j=1; j<=n; j++)
{
if(!mark[j]&&min>diss[j])
{
k=j;
min=diss[j];
}
}
mark[k]=1;
for(j=1; j<=n; j++)
{
if(!mark[j]&&map[k][j]+diss[k]<diss[j])
{
diss[j]=map[k][j]+diss[k];
}
}
}
}
int main()
{
int m,l,max;
while(~scanf("%d%d%d",&n,&m,&x))
{
max=-INF;
memset(map,INF,sizeof(map));
while(m--)
{
scanf("%d%d%d",&i,&j,&l);
map[i][j]=l;
}
Dijkstra();//去的路径;
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{//单向路,反转;
swap(map[i][j],map[j][i]);
}
}
Dijkstraa();//回来的路径;
for(i=1; i<=n; i++)
{
if(dis[i]+diss[i]>max)
max=dis[i]+diss[i];
}
printf("%d\n",max);
}
return 0;
}