题目链接
思路
$$ 生成树,注意读题,看清变量代表的是什么。 $$
时间复杂度
$$ O((N + M)log(N + M)) $$
代码
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
class DSU {
public:
vector<int> p, r;
void init(int n) {
p.resize(n + 10);
r.resize(n + 10);
for (int i = 0; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int x) {
if (x == p[x]) {
return x;
} else {
return p[x] = find(p[x]);
}
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) {
r[x]++;
}
}
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
};
DSU dsu;
const int MAXN = 5e4 + 10;
int a[MAXN], b[MAXN], c[MAXN], id[MAXN];
bool cmp(int x, int y) {
return c[x] > c[y];
}
int main() {
int T;
scanf("%d", &T);// don't forget &
while (T--) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);// don't forget &
dsu.init(n + m);
for (int i = 1; i <= k; i++) {
scanf("%d%d%d", &a[i], &b[i], &c[i]);// don't forget &
id[i] = i;
b[i] += n;
}
sort(id + 1, id + 1 + k, cmp);
long long w = 0;
for (int i = 1; i <= k; i++) {
int x = id[i];
if (!dsu.same(a[x], b[x])) {
w += c[x];
dsu.unite(a[x], b[x]);
}
}
printf("%lld\n", 10000LL * (n + m) - w);
}
return 0;
}