P3402-[模板]可持久化并查集【主席树】
生活随笔
收集整理的這篇文章主要介紹了
P3402-[模板]可持久化并查集【主席树】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正題
題目鏈接:https://www.luogu.org/problemnew/show/P3402
題目大意
解題思路
正常的并查集,不使用路徑壓縮,但是使用按秩合并,將深度小的合并到深度大的上面。
用主席樹維護即可。
codecodecode
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=2e5+100; struct Tree_node{int ls,rs,l,r,deep,fa; }; int n,m,cnt,root[N],edt; struct Keep_tree{Tree_node t[N*40];void Build(int &x,int l,int r){x=++cnt;t[x].l=l;t[x].r=r;if(l==r){t[x].fa=l;return;}int mid=(t[x].l+t[x].r)/2;Build(t[x].ls,l,mid);Build(t[x].rs,mid+1,r);}Tree_node Query(int x,int pos){if(t[x].l==t[x].r)return t[x];if(pos<=t[t[x].ls].r) return Query(t[x].ls,pos);return Query(t[x].rs,pos);}void Insert(int x,int &y,int pos,int nef){y=++cnt;t[y]=t[x];if(t[x].l==t[x].r){t[y].fa=nef;return;}if(pos<=t[t[x].ls].r) Insert(t[x].ls,t[y].ls,pos,nef);else Insert(t[x].rs,t[y].rs,pos,nef);}void add(int x,int pos){if(t[x].l==t[x].r){t[x].deep++;return;}if(pos<=t[t[x].ls].r) add(t[x].ls,pos);else add(t[x].rs,pos);} }Tree; Tree_node find_fa(int ed,int x) {Tree_node Fa=Tree.Query(root[ed],x);if(x==Fa.fa) return Fa;return find_fa(ed,Fa.fa); } void unionn(int x,int y) {Tree_node Fa=find_fa(edt-1,x),Fb=find_fa(edt-1,y);if(Fa.fa==Fb.fa) return;if(Fa.deep<Fb.deep) swap(Fa,Fb);Tree.Insert(root[edt-1],root[edt],Fb.fa,Fa.fa);if(Fa.deep==Fb.deep)Tree.add(root[edt],Fa.fa); } int main() {scanf("%d%d",&n,&m);Tree.Build(root[0],1,n);for(int i=1;i<=m;i++){int op,x,y;scanf("%d",&op);++edt;root[edt]=root[edt-1];if(op==1){scanf("%d%d",&x,&y);unionn(x,y);}if(op==2){scanf("%d",&x);root[edt]=root[x];}if(op==3){scanf("%d%d",&x,&y);if(find_fa(edt,x).fa==find_fa(edt,y).fa) printf("1");else printf("0");putchar('\n');}} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的P3402-[模板]可持久化并查集【主席树】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2014电脑配置(2014电脑配置400
- 下一篇: 欢乐纪中某A组赛【2019.7.8】