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 irequires 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.
题目大意:n个奶牛编号为1...n,m条单向路,所有奶牛要去编号为x奶牛的加参加派对,并从x奶牛的加回到自己的家,然后m行
每行三个数 u ,v, w,表示奶牛u到奶牛v家的距离为w,求出所有奶牛去参加并回到家所需的最短路径,最后输出最大的那个奶牛所有的距离
解题思路:dijkstra算法来解决,因为是单向路,所以很容易就可以求出源点x到每头奶牛的最短路径,然后只需要在求出每头奶牛到x的最短路径就可以了,直接求的话不好求,可以将所有的路径方向,这样再求x到每头奶牛的最短距离就是每头奶牛到x的最短距离
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1e3+10;
const int INF=0x3f3f3f3f;
int n,m,x;
int e[maxn][maxn];
int dis1[maxn],dis2[maxn],vis[maxn];
void dijkstra()
{
int MIN,v;
for(int i=1;i<=n;i++)
{
dis1[i]=e[x][i];//从x来
dis2[i]=e[i][x];//回x
}
dis1[x]=0;
vis[x]=1;
for(int k=1;k<=n;k++)
{
MIN=INF;
for(int w=1;w<=n;w++)
{
if(!vis[w]&&dis1[w]<MIN)
{
v=w;
MIN=dis1[w];
}
}
vis[v]=1;
for(int w=1;w<=n;w++)
{
if(!vis[w]&&(dis1[v]+e[v][w]<dis1[w]))
{
dis1[w]=dis1[v]+e[v][w];
}
}
}
memset(vis,0,sizeof(vis));
dis2[x]=0;
vis[x]=1;
for(int k=1;k<=n;k++)
{
MIN=INF;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&dis2[i]<MIN)
{
MIN=dis2[i];
v=i;
}
}
vis[v]=1;
for(int w=1;w<=n;w++)
{
if(!vis[w]&&dis2[w]>dis2[v]+e[w][v])
{
dis2[w]=dis2[v]+e[w][v];
}
}
}
}
int main()
{
int u,v,w;
scanf("%d%d%d",&n,&m,&x);
memset(e,INF,sizeof(e));
for(int i=1;i<=n;i++)
{
e[i][i]=0;
}
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
e[u][v]=w;
}
dijkstra();
int ans=0;
for(int i=1;i<=n;i++)
{
ans=max(ans,dis1[i]+dis2[i]);
}
cout<<ans<<endl;
return 0;
}