bzoj3674 可持久化并查集加强版

本文介绍了一种使用主席树和按秩合并策略实现的可持久化并查集算法,该算法能够处理一系列合并与回滚操作,并通过示例代码展示了如何解决特定问题。

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

bzoj3674 可持久化并查集加强版

Description:
自从zkysb出了可持久化并查集后……
hzwer:乱写能AC,暴力踩标程
KuribohG:我不路径压缩就过了!
ndsf:暴力就可以轻松虐!
zky:……

n个集合 m个操作
操作:
1 a b 合并a,b所在集合
2 k 回到第k次操作之后的状态(查询算作操作)
3 a b 询问a,b是否属于同一集合,是则输出1否则输出0
请注意本题采用强制在线,所给的a,b,k均经过加密,加密方法为x = x xor lastans,lastans的初始值为0
0 < n,m <= 2*10^5

Sample Input
5 6
1 1 2
3 1 2
2 1
3 0 3
2 1
3 1 2

Sample Output
1
0
1


主席树+按秩合并(似乎路径压缩并没有什么用QwQ)
还有 不写xor lastans竟然也能对…

#include <bits/stdc++.h>
#define N 200010
#define M 8000010
#define mid ((l+r)>>1)
using namespace std;
int n,m;

struct tree{
    tree *ch[2]; int d,dep;
    tree(){
        d=0; dep=1;
    }
}t[M],*root[N],*tail=t;

template <class Aqua>
inline void read(Aqua &s){
    s=0; char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) s=s*10+c-'0',c=getchar();
}

tree *newnode(){
    (tail+1)->ch[0]=(tail+1)->ch[1]=t;
    return ++tail;
}

void modify(tree *&cur,tree *pre,int l,int r,int pos,int d,int dep){
    cur=newnode();
    if (l==r){
        cur->d=d; cur->dep=dep;
        return;
    }
    cur->ch[0]=pre->ch[0]; cur->ch[1]=pre->ch[1];
    if (pos<=mid)
        modify(cur->ch[0],pre->ch[0],l,mid,pos,d,dep);
    else
        modify(cur->ch[1],pre->ch[1],mid+1,r,pos,d,dep);
}

tree *query(tree *cur,int l,int r,int pos){
    if (l==r) return cur;
    if (pos<=mid)
        return query(cur->ch[0],l,mid,pos);
    else
        return query(cur->ch[1],mid+1,r,pos);
}

tree *Query(tree *cur,int x){
    for (tree *f;;x=f->d){
        f=query(cur,1,n,x);
        if (f->d==x)
            return f;
    }
}

void pre(){
    t->ch[0]=t->ch[1]=root[0]=t;
    for (int i=1;i<=n;i++)
        modify(root[0],root[0],1,n,i,i,1);
}

int main(){
    read(n),read(m);
    pre();
    int op,a,b,las(0); tree *x,*y;
    for (int i=1;i<=m;i++){
        read(op); root[i]=root[i-1];
        if (op==1){
            read(a),read(b);
            a^=las,b^=las;
            x=Query(root[i],a),y=Query(root[i],b);
            if (x->d==y->d)
                continue;
            if (x->dep>y->dep)
                swap(x,y);
            modify(root[i],root[i],1,n,x->d,y->d,y->dep);
            if (x->dep==y->dep)
                modify(root[i],root[i],1,n,y->d,y->d,y->dep+1);
        }
        if (op==2){
            read(a); a^=las;
            root[i]=root[a];
        }
        if (op==3){
            read(a),read(b);
            a^=las,b^=las;
            x=Query(root[i],a),y=Query(root[i],b);
            las=(x->d==y->d);
            printf("%d\n",las);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值