Silver Cow Party POJ - 3268 两遍dij

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 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.

扫描二维码关注公众号,回复: 3403255 查看本文章

直接扫两发就好了

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int map[1005][1005],dis1[1005],dis2[1005],visit[1005];
int n,m,x;

void dijstra2()//源点x到各点的最短路 
{
	for(int i=1;i<=n;i++)
	{
		dis2[i]=(i==x)?0:map[x][i];
		visit[i]=0;
	}
	visit[x]=1;
	for(int i=1;i<=n;i++)
	{
		int s=0,minn=9999999;
		for(int j=1;j<=n;j++)
		{
			if(!visit[j]&&minn>dis2[j])
			{
				minn=dis2[j];
				s=j;
			}
		}
		visit[s]=1;
		for(int j=1;j<=n;j++)
		{
			if(!visit[j]&&dis2[j]>dis2[s]+map[s][j])
			{
				dis2[j]=dis2[s]+map[s][j];
			}
		}
	}
}

void dijstra1()// 各点到源点x的最短路 其实就是把路径方向反过来 还是以x为源点 
{
	for(int i=1;i<=n;i++)
	{
		visit[i]=0;
		dis1[i]=(i==x)?0:map[i][x];
	}
	visit[x]=1;
	for(int i=1;i<=n;i++)
	{
		int s=0,minn=9999999;
		for(int j=1;j<=n;j++)
		{
			if(!visit[j]&&minn>dis1[j])
			{
				minn=dis1[j];
				s=j;
			}
		}
		visit[s]=1;
		for(int j=1;j<=n;j++)
		{
			if(!visit[j]&&dis1[j]>dis1[s]+map[j][s])
			{
				dis1[j]=dis1[s]+map[j][s];
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	while(cin>>n>>m>>x)
	{
		if(!m||!n||!x) break;
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=n;j++)
			{
				if(i==j) map[i][j]=0;
				else map[i][j]=map[j][i]=9999999;
			}	
		}
		for(int i=1;i<=m;i++)	
		{
			int s,e,p;
			cin>>s>>e>>p;
			if(map[s][e]>p)
			map[s][e]=p;
		}
		dijstra2();//从终点倒回各个农场 源点为x 
		dijstra1();	//从各点到终点 源点为x 把逆向边视为正向
		int ans=0;
		for(int i=1;i<=n;i++)
		ans=max(ans,dis1[i]+dis2[i]);
		cout<<ans<<endl;
	}
} 

猜你喜欢

转载自blog.csdn.net/weixin_41544329/article/details/82670906