C - Silver Cow Party

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.

这个题用了两次dijkstra 因为用floyd会超时
然后划重点 ::: 数组传递到函数中不要用memset初始化。

/*

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


*/ 
#include<cstdio>
#include<cstring>
#include<iostream>
#define NN 1005
using namespace std;
int dis[NN][NN];
int N,M,X;
int result=0;
int flag[NN];
void dijkstra(int res[]){
	for(int i=1;i<=N;i++){
		flag[i]=0;
		res[i]=0x3f3f3f3f;
	}
	int add=X;
	res[add]=0;
	while(1){
		flag[add]=1;
		for(int i=1;i<=N;i++){
			if(flag[i]) continue;
			res[i]=min(res[i],res[add]+dis[add][i]);
		}
		//跟新完成
		int minnum=0x3f3f3f3f;
		int minid=0;
		for(int i=1;i<=N;i++){
			if(flag[i]) continue;
			if( res[i]<minnum ) {
				minid=i;
				minnum=res[i];
			}
		}
		add=minid;
		if(add==0) break; 
	}
}
int main()
{
	int res1[NN];
	int res2[NN];

	cin>>N>>M>>X;
	memset(dis,0x3f3f3f3f,sizeof(dis));
	for(int i=0;i<M;i++)
	{
		int a,b,c;
		cin>>a>>b>>c;
		dis[a][b]=c;
	}
	dijkstra(res1);
	for(int i=1;i<=N;i++)
	{
		for(int j=i+1;j<=N;j++)
		{
			int tem=dis[i][j];
			dis[i][j]=dis[j][i];
			dis[j][i]=tem;
		}
	}
	dijkstra(res2);
//	for(int i=1;i<=N;i++) cout<<i<<' '<<res1[i]<<' '<<res2[i]<<endl;
	for(int i=1;i<=N;i++){
		result=max(result,res1[i]+res2[i]);
	}
	cout<<result<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44532671/article/details/92798730