D - 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?
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.
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 3Sample Output
10Hint
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.
题意: 求每个地方的牛 到某点聚会再回家 的最短距离中 距离最大的值。
就是求 (各点到某点(E)的最短距离+ 某点(E)到各点的最短距离 )中 最大距离
思路:最短路变形,,dis[i]=tu[star][i] 改成 dis[i]=tu[i][star]就是第二种情况
判断时改为dis[j]=max(dis[j],dis[point]+tu[j][point])即可;
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int INF=99999999;
int tu[1010][1010],book[1010],dis1[1010],dis2[1010];
int main()
{
int m,n,x,minn,flag,e1,e2,t;
scanf("%d%d%d",&n,&m,&x);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(i==j) tu[i][j]=0;
else tu[i][j]=INF;
for(int i=0; i<m; i++)
{
scanf("%d%d%d",&e1,&e2,&t);
if(tu[e1][e2]>t)
tu[e1][e2]=t;
}
for(int i=1; i<=n; i++)
{
dis1[i]=tu[x][i];
book[i]=0;
}
book[x]=1;
for(int i=1; i<n; i++)
{
minn=INF;
for(int j=1; j<=n; j++)
{
if(dis1[j]<minn&&!book[j])
{
minn=dis1[j];
flag=j;
}
}
book[flag]=1;
for(int k=1; k<=n; k++)
{
dis1[k]=min(dis1[k],dis1[flag]+tu[flag][k]);
}
}
for(int i=1; i<=n; i++)
{
dis2[i]=tu[i][x];
book[i]=0;
}
book[x]=1;
for(int i=1; i<n; i++)
{
minn=INF;
for(int j=1; j<=n; j++)
{
if(dis2[j]<minn&&!book[j])
{
minn=dis2[j];
flag=j;
}
}
book[flag]=1;
for(int k=1; k<=n; k++)
{
dis2[k]=min(dis2[k],dis2[flag]+tu[k][flag]);
}
}
int ans=-1;
for(int i=1;i<=n;i++)
{
ans=max(ans,dis1[i]+dis2[i]);
}
printf("%d\n",ans);
}
本文解决了一个有趣的问题:一群牛从各自的农场出发参加聚会并返回,求所有牛往返所需时间的最大值。采用图论中的最短路径算法进行求解。
2183

被折叠的 条评论
为什么被折叠?



