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, w;
|
|
|
|
|
const bool operator<(const Edge &t) const {
|
|
|
|
|
return w < t.w;
|
|
|
|
|
}
|
|
|
|
|
} e[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;
|
|
|
|
|
|
|
|
|
|
int el = n - 1;
|
|
|
|
|
// 录入n-1条边
|
|
|
|
|
for (int i = 0; i < el; i++) {
|
|
|
|
|
int a, b, c;
|
|
|
|
|
cin >> a >> b >> c;
|
|
|
|
|
e[i] = {a, b, c};
|
|
|
|
|
}
|
|
|
|
|
// 排序
|
|
|
|
|
sort(e, e + el);
|
|
|
|
|
|
|
|
|
|
int res = 0;
|
|
|
|
|
for (int i = 0; i < el; i++) {
|
|
|
|
|
auto x = e[i];
|
|
|
|
|
int a = find(x.a), b = find(x.b), w = x.w;
|
|
|
|
|
if (a != b) {
|
|
|
|
|
// a集合数量,b集合数量,相乘,但需要减去已经建立的最小生成权这条边
|
|
|
|
|
// w是最小的,其它的可以建立最小也得大于w,即w+1
|
|
|
|
|
res += (cnt[a] * cnt[b] - 1) * (w + 1);
|
|
|
|
|
p[a] = b; // 合并到同一集合
|
|
|
|
|
cnt[b] += cnt[a]; // b家族人数增加cnt[a]个,并查集数量合并
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// 输出
|
|
|
|
|
printf("%d\n", res);
|
|
|
|
|
}
|
|
|
|
|
return 0;
|
|
|
|
|
}
|