CF1108f 并查集

博客详细探讨了如何利用并查集解决竞赛CF1108f中的冲突处理问题,针对每种情况w进行分析,强调了在遇到同层冲突时的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每种w一起考虑,与同层冲突就加

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

using namespace std;

int n,m;
struct node
{
    int u,v,w;
    friend bool operator<(node a,node b)
    {
        return a.w>b.w;
    }
}itm[200005];

int fa[200005];

int gf(int x)
{
    if(x!=fa[x])
        return fa[x]=gf(fa[x]);
    return fa[x];
}

int main() {

    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1;i<=n;i++)
            fa[i]=i;

        priority_queue<node> q;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&itm[i].u,&itm[i].v,&itm[i].w);
            q.push(itm[i]);
        }

        int cnt=0,ans=0;
        while(!q.empty() && cnt<(n-1))
        {
            node sta=q.top();
            q.pop();

            queue<node>q1,q2;
            q1.push(sta);
            while(!q.empty() && q.top().w==sta.w)
            {
                q1.push(q.top());
                q.pop();
            }

            while(!q1.empty())
            {
                node cur=q1.front();
                q1.pop();

                int f1=gf(cur.u);
                int f2=gf(cur.v);
                if(f1!=f2)
                    q2.push(cur);
            }

            if(!q2.empty())
            {
                node cur=q2.front();
                q2.pop();

                int f1=gf(cur.u);
                int f2=gf(cur.v);
                fa[f1]=f2;
                cnt++;

                while(!q2.empty())
                {
                    node tp=q2.front();
                    q2.pop();
                    f1=gf(tp.u);f2=gf(tp.v);
                    if(f1==f2)
                        ans++;
                    else
                        fa[f1]=f2,cnt++;
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值