并查集 HDU-4424

代码:

#include <iostream>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define maxn 200005
struct Node
{
    int x;
    int y;
    long long val;
    Node(int a = 0, int b = 0, long long c = 0):x(a), y(b), val(c){}
};
Node no[maxn];
bool cmp(const Node &A, const Node &B)
{
    return A.val > B.val;
}
int fur[maxn];
int cnt[maxn];
long long sum[maxn];
int Find(int x)
{
    if(fur[x] == x) return x;
    return fur[x] = Find(fur[x]);
}
int main()
{
    int n;
    while(scanf("%d", &n) != EOF)
    {
        ///初始化数值
        for(int i = 1; i <= n; i++)
        {
            cnt[i] = 1;
            sum[i] = 0;
            fur[i] = i;
        }
        ///
        for(int i = 1; i <= n - 1; i++)
        {
            scanf("%d%d%d", &no[i].x, &no[i].y, &no[i].val);
        }
        sort(no + 1, no + n, cmp);
        for(int i = 1; i <= n - 1; i++)
        {
            int fu = Find(no[i].x);
            int fv = Find(no[i].y);
            long long x1 = no[i].val * cnt[fv] + sum[fu];
            long long x2 = no[i].val * cnt[fu] + sum[fv];
            if(x1 > x2)
            {
                fur[fv] = fu;
                cnt[fu] += cnt[fv];
                sum[fu] = x1;
            }
            else
            {
                fur[fu] = fv;
                cnt[fv] += cnt[fu];
                sum[fv] = x2;
            }
        }
        cout << sum[Find(1)] << endl;
    }
    return 0;
}

  

posted on 2017-07-25 20:51  子狼  阅读(140)  评论(0编辑  收藏  举报

导航