Algorithm/problem
백준 21924번 : 도시 건설 - MST, 크루스칼
DingCoDing
2022. 11. 30. 22:17
반응형
https://www.acmicpc.net/problem/21924
#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;
}
반응형