반응형

https://www.acmicpc.net/problem/21924

 

21924번: 도시 건설

첫 번째 줄에 건물의 개수 $N$ $(3 \le N \le 10^5 )$와 도로의 개수 $M$ $(2 \le M \le min( {N(N-1) \over 2}, 5×10^5)) $가 주어진다. 두 번째 줄 부터 $M + 1$줄까지 건물의 번호 $a$, $b$ $(1 \le a, b \le N, a ≠ b)$와 두

www.acmicpc.net

#include <bits/stdc++.h>

#define MX 100003
using namespace std;


int N, M;
int unf[MX];

int Find(int x) {
    if (unf[x] == -1) {
        return x;
    }
    return unf[x] = Find(unf[x]);
}

void merge(int a, int b) {
    a = Find(a);
    b = Find(b);

    if (a != b) {
        unf[a] = b;
    }
}

struct road {
    int a, b, c;

    bool operator<(const road &r) const {
        return c < r.c;
    }
};

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    cin >> N >> M;
    fill(unf, unf + MX, -1);

    vector<road> v;
    long long total = 0;
    long long mst = 0;
    for (int i = 0; i < M; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        v.push_back({a, b, c});
        total += c;
    }

    sort(v.begin(), v.end());

    for (int i = 0; i < M; i++) {
        auto [a, b, c] = v[i];

        a = Find(a);
        b = Find(b);
        if (a != b) {
            merge(a, b);
            mst += c;
        }
    }

    int cnt = 0;
    for (int i = 1; i <= N; i++) {
        if (unf[i] == -1)cnt++;
    }

    if (cnt > 1) {
        cout << -1;
        return 0;
    }

    cout << total - mst << '\n';


    return 0;
}
반응형

+ Recent posts