HDU 4424 conquer a new region maximum Spanning Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.