2012長春站D題||hdu4424 並查集

life4711發表於2014-09-26

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;
}



相關文章