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.
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N=1010;
const int inf=0x3f3f3f3f;
struct node
{
int id,d;
node (){}
node (int a,int b)
{
id=a;
d=b;
}
friend bool operator < (node x,node y)
{
return x.d>y.d;
}
};
vector<node>pic1[N];
vector<node>pic2[N];
priority_queue<node>que;
int s,n,m;
int dis1[N],dis2[N];
bool vis[N];
void dij(int f)
{
if(f==1)
{
for(int i=1;i<=n;i++)
dis1[i]=inf;
dis1[s]=0;
}
else
{
for(int i=1;i<=n;i++)
dis2[i]=inf;
dis2[s]=0;
}
for(int i=1;i<=n;i++)
vis[i]=false;
while(!que.empty())
que.pop();
node now,tmp;
now.id=s;
now.d=0;
que.push(now);
while(!que.empty())
{
now=que.top();
que.pop();
if(vis[now.id])
continue;
if(f==1)
{
for(int i=0;i<pic1[now.id].size();i++)
{
tmp=pic1[now.id][i];
if(dis1[tmp.id]>dis1[now.id]+tmp.d)
{
dis1[tmp.id]=dis1[now.id]+tmp.d;
que.push(node(tmp.id,dis1[tmp.id]));
}
}
}
else if(f==2)
{
for(int i=0;i<pic2[now.id].size();i++)
{
tmp=pic2[now.id][i];
if(dis2[tmp.id]>dis2[now.id]+tmp.d)
{
dis2[tmp.id]=dis2[now.id]+tmp.d;
que.push(node(tmp.id,dis2[tmp.id]));
}
}
}
vis[now.id]=true;
}
}
int main()
{
while(scanf("%d%d%d",&n,&m,&s)!=EOF)
{
for(int i=1;i<=n;i++)
{
pic1[i].clear();
pic2[i].clear();
}
int a,b,t;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&t);
pic1[a].push_back(node(b,t));
pic2[b].push_back(node(a,t));
}
dij(1);
dij(2);
int maxn=0;
for(int i=1;i<=n;i++)
{
int c=dis1[i]+dis2[i];
if(c>maxn)
maxn=c;
}
printf("%d\n",maxn);
}
return 0;
}