Silver Cow Party
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 19659 Accepted: 8987
Description
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头牛,m条有向边,这n-1头牛要去牛x家,然后再回去。
问来回都是最短路的情况下,哪头牛走的路最多。
解题思路:
从x点作为起点,dijkstra,相当于找n-1头牛回去的路径。
然后再把边调过来,从x点作为起点,相当于找n-1头牛来的路径。
最后找最大的路径。
AC代码:
#include<stdio.h>
#include<algorithm>
#include<limits.h>
const int INF = 0x3f3f3f3;
using namespace std;
int mp[1005][1005];
bool vis[1005];
int dis[1005];
int dis2[1005];
int n,m,x;
void fun()
{
for(int i = 1;i <= n;i++) dis[i] = mp[x][i],vis[i] = 0;
dis[x] = 0,vis[x] = 1;
for(int i = 1;i <= n;i++)
{
int minn = INF,index = -1;
for(int j = 1;j <= n;j++) if(!vis[j] && dis[j] < minn) minn = dis[j],index = j;
vis[index] = 1;
for(int j = 1;j <= n;j++) if(!vis[j] && dis[j] > dis[index]+mp[index][j]) dis[j] = dis[index]+mp[index][j];
}
for(int i = 1;i <= n;i++) for(int j = 1;j <= i;j++) swap(mp[i][j],mp[j][i]);
for(int i = 1;i <= n;i++) dis2[i] = mp[x][i],vis[i] = 0;
dis2[x] = 0,vis[x] = 1;
for(int i = 1;i <= n;i++)
{
int minn = INF,index = -1;
for(int j = 1;j <= n;j++) if(!vis[j] && dis2[j] < minn) minn = dis2[j],index = j;
vis[index] = 1;
for(int j = 1;j <= n;j++) if(!vis[j] && dis2[j] > dis2[index]+mp[index][j]) dis2[j] = dis2[index]+mp[index][j];
}
int maxn = -1;
for(int i = 1;i <= n;i++) maxn = max(maxn,dis[i]+dis2[i]);
printf("%d\n",maxn);
}
int main()
{
scanf("%d%d%d",&n,&m,&x);
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++) mp[i][j] = i==j?0:INF;
while(m--)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
mp[u][v] = w;
}
fun();
return 0;
}
本文介绍了一道关于寻找参加牛聚会的牛中行走距离最长的问题。通过两次使用 Dijkstra 算法来找到每头牛前往聚会及返回的最短路径,并求得总路程最长的牛。文章提供了一个 C++ 实现的示例代码。
352

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



