Luogu P3391 【模板】文艺平衡树 Splay 平衡树
https://www.luogu.org/problemnew/show/P3391
以前写过题解的入门题重写练板子。wdnmd真就 ' == ' 写成 ' = ' 了编译器不报错呗。
#include<bits/stdc++.h> using namespace std; const int maxn=100010; int n,m,rt=0,c[maxn][2]={},fa[maxn]={},rev[maxn]={},siz[maxn]={}; inline void pushup(int x){ siz[x]=siz[c[x][0]]+siz[c[x][1]]+1; } void pushdown(int x){ if(rev[x]){ swap(c[x][0],c[x][1]); rev[c[x][0]]^=1; rev[c[x][1]]^=1; rev[x]=0; } } void build(int x,int l,int r){ if(l>r)return; if(l==r){ fa[l]=x;siz[l]=1; if(l<x)c[x][0]=l; else c[x][1]=l; return; } int mid=(l+r)/2; build(mid,l,mid-1);build(mid,mid+1,r); if(mid<x)c[x][0]=mid; else c[x][1]=mid; fa[mid]=x;pushup(mid); } void rot(int x,int &k){ int pa=fa[x],gpa,l,r;gpa=fa[pa]; if(x==c[pa][0])l=0; else l=1; r=l^1; if(pa!=k){ if(c[gpa][0]==pa)c[gpa][0]=x; else c[gpa][1]=x; }else k=x; fa[x]=gpa;fa[pa]=x;fa[c[x][r]]=pa; c[pa][l]=c[x][r];c[x][r]=pa; pushup(pa); pushup(x); } /*void dfs(int x){ if(x==0)return; cout<<x<<c[x][0]<<c[x][1]<<endl; dfs(c[x][0]); dfs(c[x][1]); }*/ void splay(int x,int &k){ while(x!=k){ int pa=fa[x];int gpa=fa[pa]; if(pa!=k){ if((c[gpa][1]==pa)^(c[pa][1]==x))rot(x,k); else rot(pa,k); }rot(x,k); //dfs(rt);cout<<endl; } } int find(int v,int x){ pushdown(x); if(v==siz[c[x][0]]+1)return x; else if(v<siz[c[x][0]]+1) return find(v,c[x][0]); else return find(v-siz[c[x][0]]-1,c[x][1]); } void mrev(int l,int r){ int x=find(l,rt),y=find(r+2,rt); //cout<<x<<y<<endl; splay(x,rt);splay(y,c[x][1]); //cout<<siz[y]<<endl; rev[c[y][0]]^=1; } int main(){ scanf("%d%d",&n,&m); build(0,1,n+2);rt=(3+n)/2; for(int i=1;i<=m;++i){ int x,y; scanf("%d%d",&x,&y); if(x!=y)mrev(x,y); } for(int i=1;i<=n;++i){ printf("%d ",find(i+1,rt)-1); }cout<<endl; return 0; }