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.
题意:一群牛分别从1~n号农场赶往x号农场参加聚会,农场与农场之间的路时单向的,在n个农场之间有m条路,给出 a ,b , t表示从a号农场到b号农场需要t时间。 每头牛都会选择最短的路,问来回路上(i→x+x→i)花费时间最长的牛花费的时间是多少?
两次Dijkstra,
- 正向建图,Dijkstra求x到其他的点的最短时间,即每头牛回时的最短时间
- 反向建图,Dijkstra求其他点到x的最短时间,即每头牛去时的最短时间
- 最后将两个时间加起来,输出最大的
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
int n,m,x;
struct node{
int v,w;
node(){}
node(int vv,int ww){
v=vv;
w=ww;
}
};
struct Node{
int u,w;
Node(){}
Node(int uu,int ww){
u=uu;
w=ww;
}
bool operator<(const Node other)const{
return w>other.w;
}
};
const int N=1005;
const int Inf=999999999;
vector<node> G1[N],G2[N];
int dis1[N],dis2[N];
bool vis1[N],vis2[N];
void Dj1(){//回
priority_queue<Node> p;
for(int i=1;i<=n;i++){
dis1[i]=Inf;
vis1[i]=false;
}
dis1[x]=0;
p.push(Node(x,0));
while(!p.empty()){
Node t=p.top();
p.pop();
int u=t.u;
if(vis1[u]) continue;
vis1[u]=true;
for(int i=0;i<G1[u].size();i++){
node t=G1[u][i];
int v=t.v;
int w=t.w;
if(dis1[v]>dis1[u]+w){
dis1[v]=dis1[u]+w;
p.push(Node(v,dis1[v]));
}
}
}
}
void Dj2(){//去
priority_queue<Node> p;
for(int i=1;i<=n;i++){
dis2[i]=Inf;
vis2[i]=false;
}
dis2[x]=0;
p.push(Node(x,0));
while(!p.empty()){
Node t=p.top();
p.pop();
int u=t.u;
if(vis2[u]) continue;
vis2[u]=true;
for(int i=0;i<G2[u].size();i++){
node t=G2[u][i];
int v=t.v;
int w=t.w;
if(dis2[v]>dis2[u]+w){
dis2[v]=dis2[u]+w;
p.push(Node(v,dis2[v]));
}
}
}
}
int main(){
int u,v,w;
while(~scanf("%d%d%d",&n,&m,&x)){
for(int i=1;i<=m;i++){
scanf("%d%d%d",&u,&v,&w);
G1[u].push_back(node(v,w));
G2[v].push_back(node(u,w));
}
Dj1();
Dj2();
int smax=0;
for(int i=1;i<=n;i++){
if(smax<dis1[i]+dis2[i]){
smax=dis1[i]+dis2[i];
}
}
printf("%d\n",smax);
}
return 0;
}