HDU 4427 Conquer a New Region(思维 并查集)

题意:给你n个点,n-1条带权无向边(一棵树),定义两点之间的承载能力是他们之间路径上的最小承载能力。找出

一点,使得其余n-1个点到该点的承载能力之和最大。


思路:因为a和b之间的承载能力是它们之间承载量的最小值,所以先将边按承载量从大到小排序。每次合并A,B两

集合时,它们之间的承载量为当前最小,假如A合并到B,则和为sum[A]+cnt[B]*w, B合并到A为sum[B]+cnt[A]*w, 

选择往大的那个方向合并。


代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
int pre[maxn];
ll sum[maxn], cnt[maxn];
struct node
{
    int u, v, w;
    bool operator < (const node &a) const
    {
        return w > a.w;
    }
}edge[maxn];

int Find(int x)
{
    int r = x;
    while(pre[r] != r) r = pre[r];
    int i = x, j;
    while(i != r)
    {
        j = pre[i];
        pre[i] = r;
        i = j;
    }
    return r;
}

void join(int x, int y, int w)
{
    int a = Find(x);
    int b = Find(y);
    ll tmp1 = sum[a]+cnt[b]*w;
    ll tmp2 = sum[b]+cnt[a]*w;
    if(tmp1 >= tmp2)
    {
        pre[b] = a;
        sum[a] = sum[a]+cnt[b]*w;
        cnt[a] = cnt[a]+cnt[b];
    }
    else
    {
        pre[a] = b;
        sum[b] = sum[b]+cnt[a]*w;
        cnt[b] = cnt[b]+cnt[a];
    }
}

int main(void)
{
    int n;
    while(cin >> n)
    {
        for(int i = 0; i < maxn; i++)
            pre[i] = i, cnt[i] = 1, sum[i] = 0;
        for(int i = 0; i < n-1; i++)
            scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
        sort(edge, edge+n-1);
        for(int i = 0; i < n-1; i++)
            join(edge[i].u, edge[i].v, edge[i].w);
        printf("%lld\n", sum[Find(1)]);
    }
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值