uva11987 - Almost Union-Find

本文介绍了一种在并查集数据结构上增加新功能的方法,即支持将一个集合中的元素移动到另一个集合中。通过创建新的节点并调整集合的大小和权值,实现了元素的移动而不真正删除旧节点。

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

链接

https://vjudge.net/problem/UVA-11987

题解

这题是说在并查集原有的查询和合成的基础上,让你再支持一种把一个元素从一个集合拿出来放到另一个集合中的操作
其实我完全可以不去真的删除,而是开辟一个新的结点,并把原先的那个点的大小、权值都设为 0 0 0(相当于作废了)
然后用新开辟的点当真正的点
嗯…语言表达能力逐渐下降

代码

#include <bits/stdc++.h>
#define maxn 200010
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
typedef long long ll;
class MFS
{
    private:
    ll f[maxn], size[maxn], sum[maxn], now[maxn], tot;
    public:
    void init(ll n)
    {
        tot = n;
        for(auto i=1ll;i<=n;i++)f[i]=i, size[i]=1, sum[i]=i, now[i]=i;
    }
    ll find(ll x){return x==f[x]?x:f[x]=find(f[x]);}
    void merge(ll x, ll y)
    {
        auto fx=find(now[x]), fy=find(now[y]);
        if(fx==fy)return;
        f[fx]=fy;
        size[fy] += size[fx];
        sum[fy] += sum[fx];
    }
    void move(ll x, ll y)
    {
        auto fx=find(now[x]), fy=find(now[y]);
        if(fx==fy)return;
        size[fx]-=1, sum[fx]-=x;
        now[x] = ++tot;
        size[tot]=1, sum[tot]=x, f[tot]=tot;
        merge(x,y);
    }
    void print_info(ll x)
    {
        auto fx=find(now[x]);
        printf("%lld %lld\n",size[fx],sum[fx]);
    }
}mfs;
ll read(ll x=0)
{
    ll c, f=1;
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
    for(;isdigit(c);c=getchar())x=x*10+c-48;
    return f*x;
}
int main()
{
    ll type, x, y, n, i, m;
    while( ~scanf("%lld%lld",&n,&m) )
    {
        mfs.init(n);
        while(m--)
        {
            type = read();
            if(type==1 or type==2)x=read(), y=read();
            else x=read();
            if(type==1)
            {
                mfs.merge(x,y);
            }
            else if(type==2)
            {
                mfs.move(x,y);
            }
            else
            {
                mfs.print_info(x);
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值