链接:BZOJ 3674
3674: 可持久化并查集加强版
Time Limit: 15 Sec Memory Limit: 256 MB
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
题解:
这题依旧很水,和BZOJ3673一样,就是数据大了点,要强制在线(然则3673我也是用强制在线的做法做的)。
并查集的操作其实按秩合并就行了,主要在于空间的问题。它有个回溯操作就有可能回到之前的任何一个状态,所以我们要想办法存下所有操作之后的情况并且空间不会超。这就是可持久化并查集……
原题解据说是用可持久化平衡树。但这里我用主席树来可持久化数组,空间理论上只用nlogn(线段树的*4不要忘了)。时间的话并查集的查询logn,平衡树的查询logn,总共也就是nlogn2。这个时间复杂度可能卡不过但由于数据水(出题人懒)的缘故,还是轻松AC了……
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define N 200005
#define M 10000005
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m,cnt;
int root[N];
struct node{
int lson,rson,deep,f;
}t[M];
void build(int &root,int l,int r){
if(!root) root = ++cnt;
if(l == r){
t[root].deep = 1;
t[root].f = l;
return;
}
int mid = (l+r)>>1;
build(t[root].lson,l,mid);
build(t[root].rson,mid+1,r);
}
void link(int &root1,int root2,int l,int r,int fa,int fb){
root1 = ++cnt;
t[root1] = t[root2];
if(l == r){
t[root1].f = fb;
return;
}
int mid = (l+r)>>1;
if(mid >= fa) link(t[root1].lson,t[root2].lson,l,mid,fa,fb);
else link(t[root1].rson,t[root2].rson,mid+1,r,fa,fb);
}
int query(int root,int l,int r,int x){
if(l == r) return root;
int mid = (l+r)>>1;
if(mid >= x) return query(t[root].lson,l,mid,x);
else return query(t[root].rson,mid+1,r,x);
}
int find(int root,int x){
int f = query(root,1,n,x);
if(t[f].f == x) return f;
return find(root,t[f].f);
}
void add(int root,int l,int r,int x){
if(l == r){
t[root].deep++;
return;
}
int mid = (l+r)>>1;
if(mid >= x) add(t[root].lson,l,mid,x);
else add(t[root].rson,mid+1,r,x);
}
int main(){
n = read(); m = read(); int ans = 0;
build(root[0],1,n);
for(int i = 1;i <= m;i++){
int opt = read();
if(opt == 1){
int a = read()^ans,b = read()^ans;
int fa = find(root[i-1],a);
int fb = find(root[i-1],b);
if(t[fa].f == t[fb].f) continue;
if(t[fa].deep > t[fb].deep) swap(fa,fb);
link(root[i],root[i-1],1,n,t[fa].f,t[fb].f);
if(t[fb].deep == t[fb].deep) add(root[i],1,n,t[fb].f);
}
else if(opt == 2){
int x = read()^ans;
root[i] = root[x];
}
else{
int a = read()^ans,b = read()^ans;
root[i] = root[i-1];
int fa = find(root[i],a);
int fb = find(root[i],b);
if(t[fa].f == t[fb].f) ans = 1;
else ans = 0;
printf("%d\n",ans);
}
}
return 0;
}