Extended application of minimum spanning tree ------------ Water Splashing Festival in Corridor

Given a tree of N nodes, it is required to add several edges to expand the tree into a complete graph, and the only minimum spanning tree that satisfies the graph is still this tree.
Find the minimum sum of the weights of the added edges.
Note: All edge weights in the tree are integers, and all newly added edge weights must also be integers.
Input format The
first line contains the integer t, indicating that there are t sets of test data.
For each set of test data, the first line contains the integer N.
In the next N-1 line, three integers X, Y, and Z in each line indicate that there is an edge between the X node and the Y node, and the length is Z.
Output format
Each group of data outputs an integer, which represents the minimum sum of weights.
Each result is on a line.
Data range
1≤N≤60001≤N≤6000

1≤Z≤1001≤Z≤100
Input sample:
2
3
1 2 2
1 3 3
4
1 2 3
2 3 4
3 4 5

Sample output:
4
17

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 6010;
int n;
struct Edge{
 int a, b, w;
 bool operator<(const Edge &t)const{
    return w < t.w;
 }
}e[N];
int p[N], sizer[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 = 0; i < n - 1; i ++){
   int a, b, w;
   cin >> a >> b >> w;
   e[i] = {a, b, w};
  }
    sort(e, e + n - 1);
    for (int i = 1; i <= n; i ++)   p[i] = i, sizer[i] = 1;
    int res = 0;
  for (int i = 0; i < n - 1; i ++){
   int a = find(e[i].a), b = find(e[i].b), w = e[i].w;
   if (a != b){
    res += (sizer[a] * sizer[b] - 1) * (w + 1);
    sizer[b] += sizer[a];
    p[a] = b;
   }
  }
    cout << res << endl;
 }
  return 0;
}
164 original articles published · Like 112 · Visitors 6773

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/105443078