走廊泼水节
题目描述:
思路:
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define inf 0x3f3f3f3f
#define mod 1000000007
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d %d",&n,&m)
#define m_p(a,b) make_pair(a, b)
#define mem(a,b) memset((a),(b),sizeof(a))
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
typedef long long ll;
typedef pair <int,int> pii;
#define MAX 300000 + 50
int n, m, k, op;
struct ran{
int x, y, z;
bool operator < (const ran &a)const{
return z < a.z;
}
}tr[MAX];
int fa[MAX];
int cnt[MAX];
inline int getfa(int x){
return fa[x] == x ? x : fa[x] = getfa(fa[x]);
}
void work(){
cin >> n;
for(int i = 1; i <= n; ++i){
fa[i] = i;
cnt[i] = 1;
}
for(int i = 1; i < n; ++i){
cin >> tr[i].x >> tr[i].y >> tr[i].z;
}
sort(tr + 1, tr + n);
ll ans = 0;
for(int i = 1; i < n; ++i){
int xx = getfa(tr[i].x);
int yy = getfa(tr[i].y);
ans += (cnt[xx] * cnt[yy] - 1) * (tr[i].z + 1);
fa[xx] = yy;
cnt[yy] += cnt[xx];
}
cout << ans << endl;
}
int main(){
io;
int tt;cin>>tt;
for(int _t = 1; _t <= tt; ++_t){
work();
}
return 0;
}