hdu——3367 并查集+最大生成树【模板】

题目链接:https://cn.vjudge.net/problem/HDU-3367

In graph theory, a pseudoforest is an undirected graph in which every connected component has at most one cycle. The maximal pseudoforests of G are the pseudoforest subgraphs of G that are not contained within any larger pseudoforest of G. A pesudoforest is larger than another if and only if the total value of the edges is greater than another one’s.

题意就是在给定的图里面找到一个边权值的和最大的一个子图,这个子图要满足只有一个环的要求;

思路:可以看出它本质上是要去求边权值和最大的子图,那么就以为着整体上是利用克鲁斯卡尔算法得到的最大生成树,然后在次基础上进行一些改变,就是要得到子图上只有一个环,那么就可以想到,因为利用kru算法来实现子图 的过程中边是按照边权less的顺序给出,那么就意味着前一条边和后一条边可能不属于同一个树,于是就要先对在不在一个树分析,如果在一个树里面,那么如果想要这条边连成后不会出现两个环,只能是两个端点都不能在环中。再对两个端点不在一个树上进行分析,要想这两个端点连成后只有一个环,那么只有一下几种情况:两个端点都不在环里面,其中一个在环里面。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int maxn=1e5+10;
const int maxm=1e4+10;
struct Edge
{
    int from,val,to;
}edge[maxn];
int pre[maxm];
int cir[maxn];//用来判定是不是在一个环里面
int n,m;

int find(int x)
{
    if(pre[x]==x)
        return x;
    return  pre[x]=find(pre[x]);
}

bool cmp(Edge a,Edge b)
{
    return a.val>b.val;
}

long long solve()
{
    long long ans=0;
    sort(edge+1,edge+1+m,cmp);
    for(int i=1;i<=m;i++)
    {
        int fx=find(edge[i].from),fy=find(edge[i].to);
        if(fx==fy)
        {
            if(!cir[fx]&&!cir[fy])
            {
                ans+=edge[i].val;
                cir[fx]=cir[fy]=1;
            }
        }
        else
        {
            if(!cir[fx]&&!cir[fy])
            {
                ans+=edge[i].val;
                pre[fx]=fy;
            }
            else if(!cir[fx]||!cir[fy])
            {
                ans+=edge[i].val;
                pre[fx]=fy;
                cir[fx]=cir[fy]=1;
            }
        }
    }
    return ans;
}
 
void ini()
{
    memset(cir,0,sizeof(cir));
    for(int i=0;i<=n;i++)
        pre[i]=i;
}

int main()
{
    while(scanf("%d %d",&n,&m)&&(n||m))
    {
        ini();
        for(int i=1;i<=m;i++)
            scanf("%d %d %d",&edge[i].from,&edge[i].to,&edge[i].val);
        long long ans=solve();
        cout<<ans<<endl;
    }
    return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值