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; roadi 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, andTi. The described road runs from farmAi to farm Bi, requiringTi 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
解法很巧妙的一道题!将路径正向存在一邻接矩阵中,反向存在另一邻接矩阵(即转置)中。跑两次最短路即得解。代码如下:
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
#include<cstring>
#define F 200000000
using namespace std;
typedef struct node
{
int u,c;
node(int uu = 0,int cc = 0):u(uu),c(cc){}
bool operator < (const node &t) const
{
return c > t.c;
}
}node;
typedef struct edge
{
int u,c;
edge(int uu = 0,int cc = 0):u(uu),c(cc){}
}edge;
int n,m,x;
bool r1[1005] = {false},r2[1005] = {false};
int d1[1005],d2[1005];
vector<edge> e1[1005],e2[1005];
void dijkstra(int x)
{
for(int i = 1;i <= n; ++i) d1[i] =d2[i] = F;
priority_queue<node> q1,q2;
d1[x] = d2[x] = 0;
q1.push(node(x,0));
node t;
int u;
while(!q1.empty())
{
t = q1.top(),q1.pop();
u = t.u;
if(r1[u]) continue;
r1[u] = true;
for(int i = 0;i < e1[u].size(); ++i)
{
int v = e1[u][i].u,c = e1[u][i].c;
if(!r1[v] && d1[u] + c < d1[v])
{
d1[v] = d1[u] + c;
q1.push(node(v,d1[v]));
}
}
}
q2.push(node(x,0));
while(!q2.empty())
{
t = q2.top(),q2.pop();
u = t.u;
if(r2[u]) continue;
r2[u] = true;
for(int i = 0;i < e2[u].size(); ++i)
{
int v = e2[u][i].u,c = e2[u][i].c;
if(!r2[v] && d2[u] + c < d2[v])
{
d2[v] = d2[u] + c;
q2.push(node(v,d2[v]));
}
}
}
}
int main()
{
int l,r,w,Max = 0;
cin >> n >> m >> x;
for(int i = 0;i < m; ++i)
{
cin >> l >> r >> w;
e1[l].push_back(edge(r,w));
e2[r].push_back(edge(l,w));
}
dijkstra(x);
for(int i = 1;i <= n; ++i) Max = max(Max,d1[i]+d2[i]);
cout << Max << endl;
return 0;
}
解决一个有趣的问题:如何找到一群牛从各自农场到聚会地点再返回的最长总行走时间。通过建立两个邻接矩阵并使用Dijkstra算法求解最短路径。
&spm=1001.2101.3001.5002&articleId=54674381&d=1&t=3&u=4124eb8e8f924d009af6bfea2c08f1ce)
807

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



