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走两次:以X为起点一个正向走一个逆向走
#include<stdio.h>
#include<queue>
#include<vector>
#define INF 0x3f3f3f
#define MAX_N 1002
using namespace std;
struct edge{int to,cost;};
typedef pair<int ,int> P;//f 距离 s 顶点
int V,E,X;
int d1[MAX_N],d2[MAX_N];
int map[MAX_N][MAX_N];
bool operator <(P x,P y){
return x.first>y.first;
}
void dijkstra(int s,vector<edge> *G,int *d){
priority_queue<P> que;
fill(d,d+V+1,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();que.pop();
int v=p.second;
if(d[v]<p.first) continue;
for(int i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[v]+e.cost<d[e.to]){
d[e.to]=d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&V,&E,&X)){
vector<edge> G1[V+1],G2[V+1];
int s;edge get;
while(E--){
scanf("%d%d%d",&s,&get.to,&get.cost);
G1[s].push_back(get);
int tmp=s;
s=get.to,get.to=tmp;
G2[s].push_back(get);
}
dijkstra(X,G1,d1);
dijkstra(X,G2,d2);
int max=0;
for(int i=1;i<=V;i++){
int tmp=d1[i]+d2[i];
if(max<tmp) max=tmp;
}
printf("%d\n",max);
}
return 0;
}
SilverCowParty 最短路径问题

本文介绍了一个经典的最短路径问题——SilverCowParty。该问题要求每头牛从各自的农场出发参加聚会后再返回,需找出所有路线中所需时间最长的一条。采用Dijkstra算法分别正向和反向寻找最短路径,最终确定最长往返时间。
346

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



