【并查集】 HDU 4424 Conquer a New Region 贪心

题意:给出一棵树,树的边上都有边权值,求从一点出发的权值和最大,权值为从一点出去路径上边权的最小值  

边权从大到小排序后  每次合并

取总权值最大的为父亲节点

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cmath>
using namespace std;
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <map>
#define cler(arr, val)    memset(arr, val, sizeof(arr))
typedef long long  LL;
const int MAXN = 555;
const int MAXM = 260110;
const int INF = 0x3f3f3f3f;
const int mod = 1000000007;
struct node
{
    LL a1,b1;
    LL v;
};
struct node a[200010];
LL father[200010],rank[200010];
LL dis[200010];///边权和
LL n;
bool cmp(node c1,node c2)
{
    return c1.v>c2.v;
}
void init()
{
    for(LL i=1; i<=n; i++)
    {
        father[i]=i;
        dis[i]=0;
        rank[i]=1;///以i为根的节点数
    }
}
LL find(LL x)
{
    if(x==father[x])
        return x;
    return father[x]=find(father[x]);
}
void Union(LL x,LL y,LL w)
{
    father[x]=y;
    rank[y]+=rank[x];
    dis[y]=w;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
  //  freopen("out.txt", "w", stdout);
#endif
    LL x1,x2;
    while(~scanf("%lld",&n))
    {
        for(int i=1; i<n; i++)
            scanf("%lld%lld%lld",&a[i].a1,&a[i].b1,&a[i].v);
        init();
        sort(a+1,a+n,cmp);
        for(int i=1; i<n; i++)
        {
            LL fa=find(a[i].a1);
            LL fb=find(a[i].b1);
            x1=dis[fa]+a[i].v*rank[fb];
            x2=dis[fb]+a[i].v*rank[fa];
            if(x1>x2)
                Union(fb,fa,x1);
            else
                Union(fa,fb,x2);
        }
        printf("%lld\n",dis[find(1)]);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值