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