思路
假如两个连通块通过一条长为2的边相连,那么将它变成一个完全图需要连接它们之间所有能连的边,并且每条边的长度都是3
C++ 代码
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 100010;
int p[N],sz[N];
struct node {
int a, b;
int c;
bool operator <(const node g) {
return c < g.c;
}
}tr[N];
int find(int x) {
if (x != p[x]) p[x] = find(p[x]);
return p[x];
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i <= n + 10; i++) {
p[i] = i, sz[i] = 1;
}
for (int i = 1; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
tr[i] = { a,b,c };
}
sort(tr + 1, tr + n);
int res = 0;
for (int i = 1; i < n; i++) {
int a = tr[i].a, b = tr[i].b;
if (find(a) == find(b)) continue;
res += (sz[find(a)] * sz[find(b)] - 1) * (tr[i].c + 1);
sz[find(b)] += sz[find(a)];
p[find(a)] = find(b);
}
cout << res << endl;
}
return 0;
}