Silver Cow Party

来源:互联网 发布:徐静蕾字体字帖淘宝 编辑:程序博客网 时间:2024/05/21 13:15

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 ≤XN). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; roadi 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 farmAi 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 21 2 41 3 21 4 72 1 12 3 53 1 23 4 44 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个农厂,其中标号为x的农场要举行party,其余农场的牛要去参加,但是牛都很懒,所以不管是过去还是回来,牛都会走对于他们自己而言最短的路,要你求出所有牛中走得时间最长的一个。




解题思路:求两次最短路,第一次求x到其余各点的最短路,第二次求各点到x的最短路。前者易于解决,直接应用dijkstra或其他最短路算法即可,由于路是单向的,后者要先把路i到j变成j到i的将再执行x到其他点最短路算法。


代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#define inf 99999999

using namespace std;
int n,m,x;
int sum[1010];
int flag[1010];
int dis[1010];
int s[1010][1010];

void dijkstra(){
    memset(flag,0,sizeof(flag));
    int mins, k;
    for(int i=1; i<=n; i++){
        dis[i] = s[x][i];
    }
    dis[x] = 0;
    flag[x] = 1;
    for(int i=1; i<n; i++){
        mins = inf;
        for(int j=1; j<=n; j++){
            if(!flag[j] && mins>dis[j]){
                k = j;
                mins = dis[j];
            }
        }
        flag[k] = 1;
        sum[k] += mins;
        for(int j=1; j<=n; j++){
            if(!flag[j] && dis[j]>dis[k]+s[k][j]){
                dis[j] = dis[k]+s[k][j];
            }
        }
    }
}

int main(){
    scanf("%d %d %d",&n,&m,&x);
    int a,b,l;
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++){
            if(i==j) s[i][j] = 0;
            else s[i][j] = inf;
        }
    }
    for(int i=0; i<m; i++){
        scanf("%d %d %d",&a,&b,&l);
        s[a][b] = l;
    }
    memset(sum,0,sizeof(sum));
    dijkstra();
    int t;
    for(int i=1; i<=n; i++){
        for(int j=1; j<i; j++){
            t = s[i][j];
            s[i][j] = s[j][i];
            s[j][i] = t;
        }
    }
    dijkstra();
    int maxs = sum[1];
    for(int i=2; i<=n; i++){
        if(maxs < sum[i])
            maxs = sum[i];
    }
    printf("%d\n",maxs);
    return 0;
}



原创粉丝点击