2012长春站D题||hdu4424 并查集

http://acm.hdu.edu.cn/showproblem.php?pid=4424

Problem Description
The wheel of the history rolling forward, our king conquered a new region in a distant continent.
There are N towns (numbered from 1 to N) in this region connected by several roads. It's confirmed that there is exact one route between any two towns. Traffic is important while controlled colonies are far away from the local country. We define the capacity C(i, j) of a road indicating it is allowed to transport at most C(i, j) goods between town i and town j if there is a road between them. And for a route between i and j, we define a value S(i, j) indicating the maximum traffic capacity between i and j which is equal to the minimum capacity of the roads on the route. 
Our king wants to select a center town to restore his war-resources in which the total traffic capacities from the center to the other N - 1 towns is maximized. Now, you, the best programmer in the kingdom, should help our king to select this center.
 

Input
There are multiple test cases.
The first line of each case contains an integer N. (1 <= N <= 200,000)
The next N - 1 lines each contains three integers a, b, c indicating there is a road between town a and town b whose capacity is c. (1 <= a, b <= N, 1 <= c <= 100,000)
 

Output
For each test case, output an integer indicating the total traffic capacity of the chosen center town.
 

Sample Input
   
   
   
   
4 1 2 2 2 4 1 2 3 1 4 1 2 1 2 4 1 2 3 1
 

Sample Output
   
   
   
   
4 3
由于要所有点到这个点的权值和最大,把边按从大到小排序并插入。每条边连接两个集合, 且每次并入的边权值都是当前已并入边中最小的。那么,只要每次并入时判断是把a并入b 得到的权值和大还是b并入a得到的权值和大就可以了。并查集维护集合的元素个数和总的 权值。
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

typedef long long LL;

int n,m,k,fa[200005],num[200005],x,y;
LL sum[200005];

struct note
{
    int u,v,w;
}edge[200005];

bool cmp(note a,note b)
{
    return a.w>b.w;
}

void init()
{
    for(int i=0;i<=n;i++)
    {
        fa[i]=i;
        num[i]=1;
        sum[i]=0;
    }
}

int find(int x)
{
    if(x==fa[x])
        return x;
    return fa[x]=find(fa[x]);
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<n;i++)
            scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
        sort(edge+1,edge+n,cmp);
        LL ans=-1;
        init();
        for(int i=1;i<n;i++)
        {
            int x=find(edge[i].u);
            int y=find(edge[i].v);
            LL xx=sum[x]+(LL)edge[i].w*num[y];
            LL yy=sum[y]+(LL)edge[i].w*num[x];
            if(xx<yy)
            {
                fa[x]=y;
                num[y]+=num[x];
                sum[y]=yy;
            }
            else
            {
                fa[y]=x;
                num[x]+=num[y];
                sum[x]=xx;
            }
            ans=max(ans,max(xx,yy));
        }
        printf("%I64d\n",ans);
    }
    return 0;
}



你可能感兴趣的:(2012长春站D题||hdu4424 并查集)