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.
题意描述:这题大概意思就是有n和农场,农场之间都是单向路,其他农场的奶牛需要到指定的农场,牛只会走最短路,求出来回花费时间最长的牛所花费的时间。
解题思路:这道题吧,本身就是一个Dijkstra算法的模板题,指定的农场为源点,正序,逆序求出最短路,然后相加比较即可。
本人初学者,代码不标准请见谅。
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
#define inf 9999999
int ch[2000][2000],b[2000],dis[2000],dis1[2000],da;
int main()
{
int t,n,i,j,x,y,z,xiao,u,v,k;
while(scanf("%d%d%d",&n,&t,&k)!=EOF)
{
da=-1;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
ch[i][j]=0;
else ch[i][j]=inf;
}
}
for(i=0;i<t;i++)
{
scanf("%d%d%d",&x,&y,&z);
if(z<ch[x-1][y-1])
{
ch[x-1][y-1]=z;
}
}
for(i=0;i<n;i++) //初始状态下每个点到源点的距离。从指定农场回去
{
dis[i]=ch[k-1][i];
}
for(i=0;i<n;i++)
b[i]=0;
b[k-1]=1; //标记源点
for(i=0;i<n-1;i++)
{
xiao=inf;
for(j=0;j<n;j++)
{
if(b[j]==0&&dis[j]<xiao)
{
xiao=dis[j];
u=j;
}
}
b[u]=1;
for(v=0;v<n;v++)
{
if(ch[u][v]<inf)
{
if(dis[v]>dis[u]+ch[u][v])
dis[v]=dis[u]+ch[u][v];
}
}
}
for(i=0;i<n;i++)//去指定农场
{
dis1[i]=ch[i][k-1];
}
for(i=0;i<n;i++)
b[i]=0;
b[k-1]=1;
for(i=0;i<n-1;i++)
{
xiao=inf;
for(j=0;j<n;j++)
{
if(b[j]==0&&dis1[j]<xiao)
{
xiao=dis1[j];
u=j;
}
}
b[u]=1;
for(v=0;v<n;v++)
{
if(ch[v][u]<inf)
{
if(dis1[v]>dis1[u]+ch[v][u])
dis1[v]=dis1[u]+ch[v][u];
}
}
}
for(i=0;i<n;i++)
{
if(dis[i]+dis1[i]>da)
da=dis[i]+dis1[i];
}
printf("%d\n",da);
}
return 0;
}