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,求出距离,然后加和求最大的距离~
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;
int n, m, t;
int ma[1212][1212];
int v[2121];
int dis[2121];
int way[1211];//存储第一次的距离
void Dijkstra()
{
for(int i=1;i<=n;i++)
{
v[i] = 0;
dis[i] = ma[t][i];
}
v[t] = 1;
int point, minx;
for(int i=1;i<=n;i++)
{
point = i;
minx = INF;
for(int j=1;j<=n;j++)
{
if(minx>dis[j]&&v[j]==0)
{
minx = dis[j];
point = j;
}
}
v[point] = 1;
for(int j = 1;j<=n;j++)
{
if(v[j]==0&&dis[j]>ma[point][j]+dis[point])
dis[j] = ma[point][j] + dis[point];
}
}
}
int main()
{
int a, b, c;
while(~scanf("%d %d %d", &n, &m, &t))
{
for(int i=0;i<=n;i++)//初始化
{
for(int j=0;j<=n;j++)
{
if(i!=j)
ma[i][j] = INF;
else
ma[i][j] = 0;
}
}
for(int i=0;i<m;i++)
{
scanf("%d %d %d", &a, &b, &c);
if(ma[a][b]>c)
ma[a][b] = c;
}
Dijkstra();
for(int i=1;i<=n;i++)//存储距离
{
way[i] = dis[i];
}
for(int i=1;i<=n;i++)//矩阵的转置
{
for(int j=i+1;j<=n;j++)
{
int temp = ma[i][j];
ma[i][j] = ma[j][i];
ma[j][i] = temp;
}
}
Dijkstra();//再次
int ans = 0;
for(int i=1;i<=n;i++)//寻找最长距离
{
if(i!=t)
ans = max(ans, dis[i]+way[i]);
}
cout<<ans<<endl;//输出
}
return 0;
}
本文介绍了一种使用两次Dijkstra算法解决特定问题的方法:计算农场间参加聚会的牛往返所需的最长时间。首先计算各农场到聚会地点的最短路径,然后通过矩阵转置更新路径信息,再次运行Dijkstra算法来找出所有牛往返的最大时间。
2181

被折叠的 条评论
为什么被折叠?



