You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.4 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 6010;
struct Edge {
2 years ago
int a, b, c;
2 years ago
const bool operator<(const Edge &t) const {
2 years ago
return c < t.c;
2 years ago
}
2 years ago
} edge[N];
2 years ago
int n;
2 years ago
2 years ago
int cnt[N]; // 配合并查集使用的,记录家族人员数量
int p[N]; // 并查集
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> n;
2 years ago
for (int i = 1; i <= n; i++) p[i] = i, cnt[i] = 1; // 并查集初始化
2 years ago
// 录入n-1条边
2 years ago
int el = n - 1;
2 years ago
for (int i = 0; i < el; i++) {
int a, b, c;
cin >> a >> b >> c;
2 years ago
edge[i] = {a, b, c};
2 years ago
}
// 排序
2 years ago
sort(edge, edge + el);
2 years ago
int res = 0;
for (int i = 0; i < el; i++) {
2 years ago
int a = find(edge[i].a), b = find(edge[i].b), c = edge[i].c;
2 years ago
if (a != b) {
// a集合数量b集合数量相乘但需要减去已经建立的最小生成权这条边
2 years ago
// c是最小的其它的可以建立最小也得大于c,即c+1
2 years ago
res += (cnt[a] * cnt[b] - 1) * (c + 1);
2 years ago
p[a] = b; // 合并到同一集合
cnt[b] += cnt[a]; // b家族人数增加cnt[a]个,并查集数量合并
}
}
// 输出
2 years ago
cout << res << endl;
2 years ago
}
return 0;
}