Codeforces Round #234 (Div. 2) D. Dima and Bacteria · 并查集+Floyd

题解

题意:n个集合,在满足集合内各个点的距离为0的条件下,求集合间的最短路


在这里插入图片描述


#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int c[N];
int n, m, K;
int fa[N];
int d[505][505];

int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

int main() {
    ios::sync_with_stdio(0);

    cin >> n >> m >> K;
    for (int i = 1; i <= n; ++i) {
        fa[i] = i;
    }

    for (int i = 1; i <= K; ++i) {
        cin >> c[i];
        c[i] += c[i - 1];
    }

    for (int i = 1; i <= K; ++i) {
        for (int j = 1; j <= K; ++j) {
            d[i][j] = (i == j ? 0 : INF);
        }
    }


    for (int i = 1, u, v, w; i <= m; ++i) {
        cin >> u >> v >> w;
        int a = lower_bound(c + 1, c + K + 1, u) - c;
        int b = lower_bound(c + 1, c + 1 + K, v) - c;

        d[a][b] = d[b][a] = min(d[a][b], w);

        if (!w) {
        	//将集合最后一个元素作为father
            int fx = find(u), fy = find(v);
            if (fy > fx) fa[fx] = fy;
            else fa[fy] = fx;
        }
    }

    for (int i = 1; i <= K; ++i) {
        int father = find(c[i]); //存在不同类型的集合之间的最短路为0 所以需要find()到底
        for (int j = c[i - 1] + 1; j < c[i]; ++j) {
            if (father != fa[find(j)]) {
                return cout << "No" << endl, 0;
            }
        }
    }

    for (int k = 1; k <= K; ++k) {
        for (int i = 1; i <= K; ++i) {
            for (int j = 1; j <= K; ++j) {
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
            }
        }
    }

    cout << "Yes" << endl;
    for (int i = 1; i <= K; ++i) {
        for (int j = 1; j <= K; ++j) {
            if (d[i][j] == INF) d[i][j] = -1;
            cout << d[i][j] << ' ';
        }
        cout << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值