最短路径__Silver Cow Party ( Poj 3268 )

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

Line 1: Three space-separated integers, respectively: NM, and X
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: AiBi, and Ti. The described road runs from farm Ai to farm Bi, requiring Titime 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去,又找最短路径回到自己的农场.问哪个的奶牛的路程最长,为多少?


思路: 正向、反向建边.两次Dijkstra 算法即可.



#include <stdio.h>
#include <string.h>
#include <math.h>
#define INF 99999999
#define N 1010
int mpt1[N][N];
int mpt2[N][N];
int dis1[N];
int dis2[N];
int visit[N];

void Dijkstra(int x,int n,int* dis,int mpt[N][N])
{
    int i,j;
    for(i = 1; i <= n ; i ++)
        dis[i] = mpt[x][i];
    memset(visit,0,sizeof(visit));
    visit[x] = 1;
    for(i = 1; i < n ; i ++)
    {
        int Minj = -1,Min = INF;
        for(j = 1; j <= n ; j ++)
        {
            if(visit[j]) continue;
            if( Min > dis[j])
            {
                Min = dis[j];
                Minj = j;
            }
        }
        if(Minj == -1)continue;
        visit[Minj] = 1;
        for(j = 1; j <= n ; j ++)
        {
            if(dis[j] > dis[Minj]+mpt[Minj][j] ) dis[j] = dis[Minj]+mpt[Minj][j];
        }
    }
}


int Min1(int a,int b)
{
	if( a < b)return a;
	return b;
}
int main()
{
	int n,m,i,j,x;
	while(scanf("%d%d%d",&n,&m,&x)!=EOF)
	{
		for(i = 1; i <= n ; i ++)
		{
			for(j = 1; j <= n ; j ++)
			{
				if( i == j ) mpt1[i][j] = 0,mpt2[i][j] = 0;
				else mpt1[i][j] = INF,mpt2[i][j] = INF;
			}
		}
		int u,v,len;
		for(i = 0 ; i < m ; i++)
		{
			scanf("%d %d %d",&u,&v,&len);
				mpt1[u][v] = len;
				mpt2[v][u] = len;
		}
		Dijkstra(x,n,dis1,mpt1);
		Dijkstra(x,n,dis2,mpt2);

		int ans = 0;
		for(i = 1 ; i <= n ; i ++)
        {
            if(ans < dis1[i] + dis2[i]) ans = dis1[i] + dis2[i];
        }
        printf("%d\n",ans);
	}
	return 0;
}



你可能感兴趣的:(最短路径,dijkstra)