Each edge of a tree has a weight. Select the smallest edge of the path from the center-defined s value to the center-to the other n-1 points to obtain the s value of all points. and
Sort from big to small. merge two trees each time and set them to the largest s value of set a and set Suma B to the sumb.
Center in A or B now add the edge of the A-B to make the two sets connected because the weight of the edge of the A-B is less than or equal to the weight of the edge in the AB set, so if the merged center in a then Suma = number of points in the Suma + B set * weight of the edge of the A-B sumb = number of points in the sumb + A Set * weight of the edge of the A-B greater than 2
#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>using namespace std;const int maxn = 200010;int n;int f[maxn], rank[maxn];__int64 sum[maxn];struct edge{int u, v, w;}e[maxn];int find(int x){if(x != f[x])return f[x] = find(f[x]);return f[x];}bool cmp(edge a, edge b){return a.w > b.w;}int main(){while(scanf("%d", &n) != EOF){for(int i = 0; i < n-1; i++)scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);sort(e, e+n-1, cmp);for(int i = 0; i <= n; i++)f[i] = i, sum[i] = 0, rank[i] = 1;for(int i = 0; i < n-1; i++){int x = find(e[i].u);int y = find(e[i].v);if(x != y){if(sum[x]+(__int64)e[i].w*rank[y] > sum[y]+(__int64)e[i].w*rank[x]){f[y] = x;sum[x] = sum[x]+(__int64)e[i].w*rank[y];rank[x] += rank[y];}else{f[x] = y;sum[y] = sum[y]+(__int64)e[i].w*rank[x];rank[y] += rank[x];}}}int x = find(1);printf("%I64d\n", sum[x]);}return 0;}
HDU 4424 conquer a new region maximum Spanning Tree