Algorithm/problem
백준 2463번 : 비용 - Union & Find
DingCoDing
2022. 12. 14. 16:52
반응형
https://www.acmicpc.net/problem/2463
#include <iostream>
#include <algorithm>
#define MX 100003
typedef long long ll;
using namespace std;
const int mod = 1e9;
ll N, M, unf[MX];
ll sum = 0, ans = 0;
struct Edge {
int x, y, w;
bool operator<(const Edge &b) const {
return w > b.w;
}
};
Edge edges[MX];
int Find(int x) {
if (unf[x] < 0) return x;
return unf[x] = Find(unf[x]);
}
ll Union(int a, int b) {
ll ret = unf[a] * unf[b];
if (unf[a] < unf[b]) {
unf[a] += unf[b];
unf[b] = a;
} else {
unf[b] += unf[a];
unf[a] = b;
}
return ret;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
for (int i = 0; i < N; i++) {
unf[i] = -1;
}
for (int i = 0; i < M; i++) {
int x, y, w;
cin >> x >> y >> w;
edges[i] = {x, y, w};
sum += w;
}
sort(edges, edges + M);
for (int i = 0; i < M; i++) {
auto [x, y, w] = edges[i];
x = Find(x);
y = Find(y);
if (x != y) {
ans += sum * Union(x, y);
}
ans %= mod;
sum -= w;
}
cout << ans << '\n';
return 0;
}
반응형