天天看点

AcWing 346. 走廊泼水节

#include <bits/stdc++.h>
#define

using namespace std;
struct node {
  int a, b, w;
  friend bool operator < (const node a, const node b) {
    return a.w < b.w;
  }
}e[A];
int T, n, m, siz[A], fa[A];
int find(int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}

int main(int argc, char const *argv[]) {
  cin >> T;
  while (T--) {
    scanf("%d", &n); int ans = 0;
    for (int i = 1; i <= n; i++) fa[i] = i, siz[i] = 1;
    for (int i = 1; i < n; i++) scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].w);
    sort(e + 1, e + n);
    for (int i = 1; i < n; i++) {
      int fx = find(e[i].a), fy = find(e[i].b);
      if (fx == fy) continue;
      ans += abs(siz[fx] * siz[fy] - 1) * (e[i].w + 1);
      fa[fy] = fx; siz[fx] += siz[fy];
    }
    cout << ans << endl;
  }
  return 0;
}