zoj 3659

题解:这道题是一道树的题,但是解法其实和树没什么关系。首先将边从大到小排列,然后依次插入到并查集中再依次结合,判断哪种插入的边怎样打掉集合才是最优的。然后依次计算既可
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 200000 + 100;
int fa[maxn];
struct node
{
    int to, next;
    int len;
} p[maxn];
int e;
struct nod
{
    int num;
    long long sum;
} pp[maxn];
void init()
{
    memset(fa, -1, sizeof(fa));
    e = 0;
    for (int i = 0; i < maxn; i ++)
    {
        pp[i].num = 1;
        pp[i].sum = 0;
    }
}
int findnum(int x)
{
    if (fa[x] == -1)
        return x;
    return fa[x] = findnum(fa[x]);
}
bool cmp(node x, node y)
{
    return x.len > y.len;
}
long long ans;
void unio(int x, int y, int len)
{
    int xx = findnum(x);
    int yy = findnum(y);
     // cout <<"xx:"<<xx<<"sum:" <<pp[xx].sum <<endl;
    //pp[xx].num = pp[xx].num + pp[yy].num;
    // cout <<"xx:"<<xx<<"num:"<< pp[xx].num <<endl;
    pp[xx].sum = max(pp[xx].sum + (long long)len * pp[yy].num, pp[xx].num * (long long)len + pp[yy].sum);
    //cout <<"xx:"<<xx<<"sum:" <<pp[xx].sum <<endl;
    pp[xx].num = pp[xx].num + pp[yy].num;
    // cout <<"xx:"<<xx<<"num:"<< pp[xx].num <<endl;
    ans = max(pp[xx].sum, ans);
    fa[yy] = xx;
}
int main()
{
    int n;
    int a, b, c;
    while (~scanf("%d", &n)) {
        init();
        for (int i = 0; i < n - 1; i ++)
        {
            scanf("%d%d%d", &a, &b, &c);
            p[e].to = a;
            p[e].next = b;
            p[e].len = c;
            e ++;
        }
        ans = 0;
        sort(p, p + e, cmp);
        for (int i = 0; i < e; ++i)
        {
            unio(p[i].to, p[i].next, p[i].len);

        }
        printf("%lld\n", ans);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值