https://www.luogu.org/problemnew/show/P3391
题目背景
这是一道经典的Splay模板题——文艺平衡树。
题目描述
您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 4 1
输入输出格式
输入格式:
第一行为n,m n表示初始序列有n个数,这个序列依次是(1,2, \cdots n-1,n)(1,2,⋯n−1,n) m表示翻转操作次数
接下来m行每行两个数 [l,r][l,r] 数据保证 1 \leq l \leq r \leq n1≤l≤r≤n
输出格式:
输出一行n个数字,表示原始序列经过m次变换后的结果
n,m≤100000
!!!记得dfs时要pushdown
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+500;
const int INF=1e9;
int n,m,tot,root;
int val[maxn],f[maxn],ch[maxn][2],rev[maxn],sz[maxn];
void update_rev(int rt)
{
if(rt)
{
swap(ch[rt][0],ch[rt][1]);
rev[rt]=rev[rt]^1;
}
}
void pushdown(int rt)
{
if(!rt) return;
if(rev[rt])
{
update_rev(ch[rt][0]);
update_rev(ch[rt][1]);
rev[rt]=0;
}
}
void pushup(int rt)
{
if(!rt) return;
sz[rt]=1; //只有根节点才pushup
if(ch[rt][0]) sz[rt]=sz[ch[rt][0]]+sz[rt]; //更新节点个数和最小值
if(ch[rt][1]) sz[rt]=sz[ch[rt][1]]+sz[rt];
}
int kth(int x,int k)
{
pushdown(x);
if(sz[ch[x][0]]+1==k) return x;
else if(sz[ch[x][0]]>=k) return kth(ch[x][0],k);
else return kth(ch[x][1],k-sz[ch[x][0]]-1);
}
void newnode(int rt,int x,int fa)
{
f[rt]=fa,ch[rt][0]=ch[rt][1]=rev[rt]=0;
val[rt]=x;
sz[rt]=1;
}
void build(int &rt,int l,int r,int fa)
{
if(l>r) return;
int mid=(l+r)/2;
rt=mid;
newnode(rt,val[rt],fa);
build(ch[rt][0],l,mid-1,rt);
build(ch[rt][1],mid+1,r,rt);
pushup(rt);
}
void Rotate(int x,int p) //p==0 左旋 p==1 右旋
{
int y=f[x],z=f[y];
pushdown(z),pushdown(y),pushdown(x);
ch[y][!p]=ch[x][p],f[ch[x][p]]=y;
ch[z][ch[z][1]==y]=x,f[x]=z;
ch[x][p]=y,f[y]=x;
pushup(y),pushup(z);
}
void splay(int x,int goal) //将x节点转为goal的子节点
{
while(f[x]!=goal) //没有转到所要求的就不停止
{
int y=f[x],z=f[y];
pushdown(z),pushdown(y),pushdown(x);
if(f[y]==goal) Rotate(x,ch[y][0]==x); //如果只要再旋转一次
else
{
int p=(ch[z][0]==y);
if(ch[y][!p]==x) //zig-zig zag-zag
{
Rotate(y,p);
Rotate(x,p);
}
else //zig-zag zag-zig
{
Rotate(x,!p);
Rotate(x,p);
}
}
}
if(goal==0) root=x; //根节点改变
}
void init(int n)
{
f[0]=ch[0][0]=ch[0][1]=rev[0]=sz[0]=0;
build(root,1,n,0);
}
void Reverse(int l,int r)
{
int x=kth(root,l-1),y=kth(root,r+1);
splay(x,0),splay(y,x);
update_rev(ch[y][0]);
}
void dfs(int rt)
{
pushdown(rt);
if(ch[rt][0]) dfs(ch[rt][0]);
if(rt!=1&&rt!=n+2) cout<<val[rt]<<" ";
if(ch[rt][1]) dfs(ch[rt][1]);
}
int main()
{
scanf("%d%d",&n,&m);
val[1]=val[n+2]=INF;
for(int i=2;i<=n+1;i++) val[i]=i-1;
init(n+2);
for(int i=1;i<=m;i++)
{
int l,r;
scanf("%d%d",&l,&r);
Reverse(l+1,r+1);
}
dfs(root);
return 0;
}