POJ-1125 Stockbroker Grapevine floyd

计算出是否存在某个源点发出的信息能够到达所有其他点,并且输出满足该情况下的整个路径中最长路径最小的那个源点以及那条最长的边。

floyd直接计算,在通过遍历整个二维数组来确定这个最后结果。

代码如下:

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAXN 105
using namespace std;

// 自己到自己的距离要赋值成零

int N, G[MAXN][MAXN];

void floyd()
{
    for (int k = 1; k <= N; ++k) {
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                if (G[i][k] != INF && G[k][j] != INF) {
                    G[i][j] = min(G[i][j], G[i][k]+G[k][j]);
                }
            }
        }
    }
}

int main()
{
    int M, x, y, flag, Max, yes, ans, p;
    while (scanf("%d", &N), N) {
        yes = 0;
        ans = 0x3f3f3f3f;
        memset(G, 0x3f, sizeof (G));
        for (int i = 1; i <= N; ++i) {
            scanf("%d", &M);
            for (int j = 0; j < M; ++j) {
                scanf("%d %d", &x, &y);
                G[i][x] = y; 
            }
            G[i][i] = 0;
        }
        floyd();
        for (int i = 1; i <= N; ++i) {
            flag = 0;
            Max = -1;
            for (int j = 1; j <= N; ++j) {
                if (G[i][j] == 0x3f3f3f3f) {
                    flag = 1;
                    break;
                }
                Max = max(Max, G[i][j]);
            }
            if (!flag) {
                yes = 1;
                if (Max < ans) {
                    p = i;
                    ans = Max;
                }
            }
        }
        printf(!yes ? "disjoint\n" : "%d %d\n", p, ans);
    }
    return 0;
}
posted @ 2012-07-01 12:06  沐阳  阅读(226)  评论(0编辑  收藏  举报