POJ 3268 Silver Cow Party(巧妙的dijkstra)

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 28605   Accepted: 13007

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

题意:这个题如果你按一般的思路应该分别把去聚会和回来的最短路径加起来比较选出最大的那个。但是有一个问题就是当计算去聚会的时候,在dijkstra函数的外围还得加一个循环,时间复杂度也就是O(n3),这样一般的情况时要TLE的,所以这个时候我们思路要灵活一点,你想如果把他去的路的起点和终点调换一下,也就是把矩阵的一半进行置换运算,这样计算去的路也就换成了计算从聚会到各个农场的路了,简化了运算。

AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#define MAX 1005
#define inf 0xfffffff
using namespace std;
int n,m,x;
int map[MAX][MAX],vis[MAX],dis[MAX];
int go[MAX],back[MAX]; 
void init()
{
	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]=inf;
	}
}

void dijkstra(int st)
{
	memset(vis,0,sizeof(vis));
	int i,j,k,minn;
	vis[st]=1;
	for(i=1;i<=n;i++)
	{
		dis[i]=map[st][i];
	}
	for(i=1;i<=n;i++)
	{
		minn=inf;
		k=st;
		for(j=1;j<=n;j++)
		{
			if(!vis[j]&&minn>dis[j])
			{
				minn=dis[j];
				k=j;
			}
		}
		vis[k]=1;
		for(j=1;j<=n;j++)
		{
			if(!vis[j]&&dis[j]>map[k][j]+dis[k])
			{
				dis[j]=map[k][j]+dis[k];
			}
		}
	}
	
}
int main()
{
	int i,j;
	int a,b,time;
	scanf("%d%d%d",&n,&m,&x);
	init();
	for(i=1;i<=m;i++)
	{
		scanf("%d%d%d",&a,&b,&time);
		if(time<map[a][b])
		{
			map[a][b]=time; 
					}
	}
	int maxx=0;
	 dijkstra(x);
	for(i=1;i<=n;i++)
	{
	  
		go[i]=dis[i];
	//	printf("%d",back[i]);
		
	}
	for(i=1;i<=n;++i)//置换矩阵的值,也就是交换map[i][j]与map[j][i]的值 
		{
			for(j=i+1;j<=n;++j)
			{
				int cnt;
				cnt=map[j][i];
				map[j][i]=map[i][j];
				map[i][j]=cnt;
			}
		}
		dijkstra(x);
		for(i=1;i<=n;i++)
		{
			back[i]=dis[i]+go[i];
			if(maxx<back[i])
			maxx=back[i];
		}
	printf("%d",maxx);
	
	
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/zvenWang/article/details/81366786