Silver Cow Party(兩次Dijstra)
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;
}