Silver Cow Party(dijkstra)

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.

题意给n个点的位置,m条单项边,给出目的地X,从除X外的其他点到X,并到达后返回,问你在奶牛在选着最短路径时

哪个点的来回距离最长,是多少;可以这样考虑,找出x到其他点的最短路,再将地图反转,再从x走出最短路,求出的即

从其他点走到x点的最短距离,两次的答案分别用两个数组存到每一个点的距离,然后取两个数组某点的和最大值;

如果不是数据范围,floyd来做是极好的。

#include<iostream>
#include<stdio.h>
#include<algorithm>
const int INF = 0x3f3f3f3f;
using namespace std;
int n,s;
int a[1010],b[1010];  //a用来存终点到其他点的距离,b用来存其他点到终点的距离
int map[1010][1010];
int vis[1010];
inline void dijkstra(int d[]){
	for (int i = 1; i <= n; i++)
		d[i] = map[s][i];
	vis[s] = 1;
	for (int i = 1; i < n; i++)
	{
		int MIN = INF,k=-1;
		for (int j = 1;j <= n; j++)
		{
			if (!vis[j] && d[j] < MIN)
				MIN = d[j],k=j;
		}
		vis[k] = 1;
		for (int j = 1; j <= n; j++)
		{
			if (!vis[j])
				d[j] = min(d[j], MIN + map[k][j]);
		}
	}
}
int main(){
	 int m;
	 while (~scanf("%d%d%d", &n, &m, &s))
	 {
		 memset(a, 0, sizeof a);
		 memset(b, 0, sizeof b);
		 memset(vis, 0, sizeof vis);
		 memset(map, INF, sizeof map);
		 for (int i = 1; i <= n; i++)
			 map[i][i] = 0;
		 while (m--)
		 {
			 int x, y, v;
			 scanf("%d%d%d", &x, &y, &v);
			 if (v < map[x][y])
				 map[x][y] = v;
		 }
		 dijkstra(a);
		 for (int i = 1; i <= n; i++)   //将矩阵反转,从x到y走的距离即反为y到x的距离,再进行一次dijkstra,求出的即是其他点到终点的距离
			 for (int j = i+1; j <= n; j++)
			 {
				 swap(map[i][j], map[j][i]);
			 }
		 memset(vis, 0, sizeof vis);
		 dijkstra(b);
		 int ans = 0;
		 for (int i = 1; i <= n; i++)
			 ans = max(ans, a[i] + b[i]);//取最短情况下的最大的值
		 cout << ans << endl;
	 }
	return 0;
}

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值