可持久化并查集模板
Posted goto_1600
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了可持久化并查集模板相关的知识,希望对你有一定的参考价值。
//#pragma GCC target("avx")
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
//#pragma GCC optimize("Ofast")
// created by myq
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
typedef long long ll;
#define x first
#define y second
typedef pair<int,int> pii;
const int N = 200010;
const int mod=998244353;
inline int read()
{
int res=0;
int f=1;
char c=getchar();
while(c>'9' ||c<'0')
{
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
res=(res<<3)+(res<<1)+c-'0';
c=getchar();
}
return res;
}
int n;
struct node{
int l;
int r;
int val;
}tr[N*40*2];
int rootfa[N];
int rootdep[N];
int cnt;int idx;
int tot;
void build(int &u,int l,int r){
u=++idx;
if(l==r){
tr[u].val=l;
return ;
}
int mid=l+r>>1;
build(tr[u].l,l,mid);
build(tr[u].r,mid+1,r);
}
void modify(int &u,int q,int l,int r,int x,int d){
u=++idx;
tr[u]=tr[q];
if(l==r){
tr[u].val=d;
return ;
}
int mid=l+r>>1;
if(x<=mid) modify(tr[u].l,tr[q].l,l,mid,x,d);
else modify(tr[u].r,tr[q].r,mid+1,r,x,d);
}
int query(int u,int l,int r,int x){
if(l==r){
return tr[u].val;
}
int mid=l+r>>1;
if(x<=mid) return query(tr[u].l,l,mid,x);
else return query(tr[u].r,mid+1,r,x);
}
int find(int ver,int x){
int fa=query(rootfa[ver],1,n,x);
if(fa==x) return x;
else return find(ver,fa);
}
void merge(int ver,int x,int y){
int fx=find(ver-1,x);
int fy=find(ver-1,y);
if(fx==fy){
rootfa[ver]=rootfa[ver-1];
rootdep[ver]=rootdep[ver-1];
}
else{
int depx=query(rootdep[ver-1],1,n,fx);
int depy=query(rootdep[ver-1],1,n,fy);
if(depx>depy)
{
modify(rootfa[ver],rootfa[ver-1],1,n,fy,fx);
rootdep[ver]=rootdep[ver-1];
}
else if(depx<depy){
modify(rootfa[ver],rootfa[ver-1],1,n,fx,fy);
rootdep[ver]=rootdep[ver-1];
}
else{
modify(rootfa[ver],rootfa[ver-1],1,n,fx,fy);
modify(rootdep[ver],rootdep[ver-1],1,n,fy,depy+1);
}
}
}
int main()
{
int m;
cin>>n>>m;
build(rootfa[0],1,n);
for(int ver=1;ver<=m;ver++){
int opt;
scanf("%d",&opt);
if(opt==1){
int x,y;
scanf("%d%d",&x,&y);
merge(ver,x,y);
// rootfa[ver]=rootfa[ver-1];
// rootdep[ver]=rootdep[ver-1];
}
else if(opt==2){
int k;
scanf("%d",&k);
rootfa[ver]=rootfa[k];
rootdep[ver]=rootdep[k];
}
else
{
int x,y;
scanf("%d%d",&x,&y);
rootfa[ver]=rootfa[ver-1];
rootdep[ver]=rootdep[ver-1];
x=find(ver,x);
y=find(ver,y);
// cout<<x<<" "<<y<<endl;
if(x==y) puts("1");
else puts("0");
}
}
return 0;
}
/**
* In every life we have some trouble
* When you worry you make it double
* Don't worry,be happy.
**/
以上是关于可持久化并查集模板的主要内容,如果未能解决你的问题,请参考以下文章