Skip to content

AcWing1143 联络员

问题描述

link

分析

参考代码

cpp
#include <bits/stdc++.h>
using namespace std;

const int N = 2010, M = 10010;

struct Edge {
    int a, b, c;

    bool operator < (const Edge& t) const {
        return c < t.c;
    }
} e[M];
int n, m, p[N];

int find(int x) {
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) p[i] = i;

    int res = 0, k = 0;
    for (int i = 0; i < m; i++) {
        int t, a, b, c; cin >> t >> a >> b >> c;

        if (t == 1) {
            p[find(a)] = find(b);
            res += c;
        } else e[k++] = {a, b, c};
    }

    sort(e, e + k);

    for (int i = 0; i < k; i++) {
        int pa = find(e[i].a), pb = find(e[i].b), c = e[i].c;
        if (pa != pb) {
            p[pa] = pb;
            res += c;
        }
    }

    cout << res << endl;

    return 0;
}