【POJ3268】Silver Cow Party(dij/矩阵转置)

Silver Cow Party

Time Limit: 2000msMemory Limit: 65536KB 64-bit integer IO format: %lld Java class name: Main

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

题目大意:老母牛开party,每只母牛都住在一个牛舍(1到n)。叫你找到所有母牛中,去到老母牛那个地方和从那个地方回来的最长的路程(母牛贼JB懒但是很聪明,不管是去还是来都是走的最短路)。输入三个数代表点数、边数、和老母牛的位置。这是个有向图 map[a][b]不一定等于map[b][a]

分析:一开始按照DIJ的思路,将从老母牛的位置X点出发,找到去其他点的最短路。然后把邻接矩阵转置(转置map[][])再从X出发DIJ一遍,找的就是其他点到X的最短路了。将两个记录最短路路程的数组按照顺序相加取最大的就搞完了。

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"

using namespace std;

const int maxn = 1e3+5;
const int INF = 0x3f3f3f3f;

int map[maxn][maxn];
int dis[maxn];
int vis[maxn];
int dd[maxn];
int n,m,x;
int a,b,time;

void dij(){
    memset(vis,0,sizeof(vis));
    memset(dis,INF,sizeof(dis));
    dis[x]=0;
    for( int i=1 ; i<=n ; i++ ){
        int u = -1;
        for( int j=1 ; j<=n ; j++ ){
            if(!vis[j]&&(u==-1||dis[j]<dis[u])){
                u=j;
            }
        }
        vis[u]=1;
        for( int j=1 ; j<=n ; j++ ){
            if(dis[j]>dis[u]+map[u][j]){
                dis[j] = dis[u] + map[u][j];
            }
        }
    }
}

int main(){
    while(~scanf("%d%d%d",&n,&m,&x)){
        memset(map,INF,sizeof(map));
        while(m--){
            scanf("%d%d%d",&a,&b,&time);
            map[a][b]=time;
        }
        dij();
        for( int i=1 ; i<=n ; i++ ){
            dd[i]=dis[i];
        }
        for( int i=1 ; i<=n ; i++ ){
            for( int j=i+1 ; j<=n ; j++ ){
                map[i][j] = map[i][j] ^ map[j][i];
                map[j][i] = map[i][j] ^ map[j][i];
                map[i][j] = map[i][j] ^ map[j][i];
            }
        }
        dij();
        int max=-1;
        for( int i=1 ; i<=n ; i++ ){
            if((dd[i]+dis[i])>max){
                max = dd[i]+dis[i];
            }
        }
        printf("%d\n",max);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/thesprit/article/details/51996659