洛谷P3402 【模板】可持久化并查集

本文介绍了一种结合并查集与线段树的数据结构优化方案,用于高效处理动态集合的合并与查询操作。通过维护每个节点的父节点和集合大小,实现了快速查找与平衡合并,避免了传统并查集在合并操作中的效率瓶颈。同时,利用线段树的特性,对集合的大小更新进行了优化,使得在处理大规模数据集时,算法的时间复杂度得到了显著降低。

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

一定注意每一次都要是 $root[cur]=root[cur-1]$,不然进行合并时如果 $a,b$ 在同一集合中就会使 $root[cur]=0$.

Code:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
//ty==1 for size, ty==0 for father

void setIO(string a){ freopen((a+".in").c_str(),"r",stdin); }

#define maxn 200005
int n,m,cur,root[maxn*4];
struct Node{ 
    int f,siz; 
    Node(int f=0,int siz=0):f(f),siz(siz){}
};
struct Segment_Tree{
    int lson[maxn*50],rson[maxn*50],fa[maxn*50],siz[maxn*50];
    int nodes;
    void build(int l,int r,int &o){
        if(l>r)return;
        o=++nodes;
        if(l==r) { siz[o]=1,fa[o]=l; return; }
        int mid=(l+r)>>1;
        build(l,mid,lson[o]), build(mid+1,r,rson[o]);
    }  
    int update(int l,int r,int o,int pos,int ty,int k){
        int oo=++nodes;
        lson[oo]=lson[o],rson[oo]=rson[o],fa[oo]=fa[o],siz[oo]=siz[o];
        if(l==r) { 
            if(ty==1) siz[oo]=k;  
            if(ty==0) fa[oo]=k;
            return oo;
        }
        int mid=(l+r)>>1;
        if(pos<=mid) lson[oo]=update(l,mid,lson[o],pos,ty,k);
        else rson[oo]=update(mid+1,r,rson[o],pos,ty,k);
        return oo;
    }
    Node query(int l,int r,int o,int pos){
        if(l==r){ return Node(fa[o],siz[o]); }
        int mid=(l+r)>>1;
        if(pos<=mid) return query(l,mid,lson[o],pos);
        else return query(mid+1,r,rson[o],pos);
    }
    Node find(int x,int state){
        Node p=query(1,n,root[state],x);
        return p.f==x?p:find(p.f,state);
    }
    void merge(int a,int b,int state){
        Node x=find(a,state), y=find(b,state);
        if(x.f==y.f) return;
        if(x.siz>y.siz) 
            root[cur]=update(1,n,root[state],x.f,1,y.siz+x.siz),root[cur]=update(1,n,root[cur],y.f,0,x.f);
        else 
            root[cur]=update(1,n,root[state],y.f,1,y.siz+x.siz),root[cur]=update(1,n,root[cur],x.f,0,y.f);
    }
    int ask(int a,int b,int state){
        Node x=find(a,state),y=find(b,state);
        if(x.f==y.f)return 1; return 0;
    }
}S;
int main(){
   // setIO("input");
    int opt,a,b,lastans=0;
    scanf("%d%d",&n,&m);
    S.build(1,n,root[0]);
    for(cur=1;cur<=m;++cur){
        scanf("%d",&opt);
        root[cur]=root[cur-1];
        switch(opt)
        {
            case 1: { scanf("%d%d",&a,&b),a^=lastans,b^=lastans,S.merge(a,b,cur-1); break;}
            case 2: { scanf("%d",&a),a^=lastans,root[cur]=root[a]; break;}
            case 3: { scanf("%d%d",&a,&b),a^=lastans,b^=lastans,lastans=S.ask(a,b,cur-1),printf("%d\n",lastans); break;}
        }
    }
    return 0;
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值