Silver Cow Party (djk最短路)

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define N 1010
#define M 100010
#define INF 0x3f3f3f3f
int n,m,x;
int mp[N][N];
int dis1[N],dis2[N];
bool vis[N];
void init(int n)
{
	for(int i=1;i<=n;i++) 
	{
		for(int j=1;j<=n;j++)
		{
			if(i==j) mp[i][j]=0;
			else mp[i][j]=INF;
		}
	}
 }
void getmap(int m)
{
	int u,v,val; 
	while(m--)
	{
		scanf("%d%d%d",&u,&v,&val);
		 mp[u][v]=min(mp[u][v],val);
	}
}
void djk(int st,int dis1[])
{
	for(int i=1;i<=n;i++)
	{
		vis[i]=false;
		dis1[i]=mp[st][i];
	}
	vis[st]=true;
	for(int i=1;i<n;i++)
	{
		int mn=INF,id=-1;
		for(int j=1;j<=n;j++)
		{
			if(!vis[j]&&dis1[j]<mn)
			{
				mn=dis1[j];id=j;
			}
		}
		if(id==-1) break;
		vis[id]=true;
		for(int j=1;j<=n;j++)
		{
			if(!vis[j]&&mp[id][j]!=INF)
			{
				if(dis1[j]>dis1[id]+mp[id][j])
				{
					dis1[j]=dis1[id]+mp[id][j];
				}
			}
		}
	}
}
int main()
{
	int i,j,t1;
	scanf("%d%d%d",&n,&m,&x);
	init(n);
	getmap(m);
//	memset(dis1,INF,sizeof(dis1));
//	memset(dis2,INF,sizeof(dis2));
	djk(x,dis1);
	bool qwe[N][N];
	memset(qwe,false,sizeof(qwe));
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=n;j++)//下面这个是精华,就是直接换一下方向 
		{
			if(!qwe[i][j]&&!qwe[j][i])
			{ //eg:a-x val=8;x-a val=9,可以直接换成 x-a val=8,a-x val=9;之后可以直接求出x到各点的最短距离即可。 
				qwe[i][j]=true;qwe[j][i]=true;
					t1=mp[i][j];
					mp[i][j]=mp[j][i];
					mp[j][i]=t1;
			}
		}
	}
	int w=0; 
	djk(x,dis2);
	for(int i=1;i<=n;i++)
	{
		if(dis1[i]+dis2[i]>w)
		w=dis1[i]+dis2[i];
		
	}
	printf("%d\n",w);
	return 0;
	
	
}

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.

猜你喜欢

转载自blog.csdn.net/qq_42434171/article/details/81676887