平衡树【Splay】区间翻转【模板】

luoguP3391一道模板题
学习了 s p l a y splay splay区间翻转的姿势

具体就是先建两个虚拟节点 1 , n + 2 1,n+2 1,n+2,然后按节点下标 + 1 +1 +1将区间树建出来,这时候排名为 k k k的就是第 k k k个数。
翻转的时候先把 ( l + 1 ) − 1 (l+1)-1 (l+1)1提到根,再把 ( r + 1 ) + 1 (r+1)+1 (r+1)+1提到根的右儿子,然后 ( r + 1 ) + 1 (r+1)+1 (r+1)+1的左儿子就是一整个区间了,然后把它打上 r e v rev rev标记, f i n d find find查询排名的时候记得下放一下标记, p u s h d o w n pushdown pushdown的时候只要 s w a p swap swap一下左右儿子就好啦。

昨天写的 s p l a y splay splay是直接旋到根的,今天写了一下旋转到固定点的 q w q qwq qwq

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define N 100005
using namespace std;
int n,m,ch[N][2],siz[N],fa[N],root,rev[N];

inline int rd(){
	int x=0,f=1;char c=' ';
	while(c<'0' || c>'9') f=c=='-'?-1:1,c=getchar();
	while(c<='9' && c>='0') x=x*10+c-'0',c=getchar();
	return x*f;
}

inline void pushup(int x){
	siz[x]=siz[ch[x][0]]+siz[ch[x][1]]+1;
}
inline void pushdown(int x){
	if(rev[x]){
		swap(ch[x][0],ch[x][1]);
		rev[ch[x][0]]^=1,rev[ch[x][1]]^=1; rev[x]=0;
	}
}
inline int get(int x){return ch[fa[x]][1]==x;}
inline void rotate(int x,int &k){
	int old=fa[x],oldf=fa[old],wh=get(x);
	if(old==k) k=x;
	else ch[oldf][ch[oldf][1]==old]=x;
	fa[ch[x][wh^1]]=old; ch[old][wh]=ch[x][wh^1];
	fa[old]=x; ch[x][wh^1]=old; fa[x]=oldf;
	pushup(old); pushup(x);
}
inline void splay(int x,int &k){//将x旋转到k
	while(x!=k){
		int y=fa[x],z=fa[y];
		if(y!=k){
			if(get(x)==get(y)) rotate(y,k);
			else rotate(x,k);
		}
		rotate(x,k); 
	}
}

void build(int x,int l,int r){//建树 
	if(l>r) return;
	int mid=(l+r)>>1;
	if(mid<x) ch[x][0]=mid;
	else ch[x][1]=mid;
	fa[mid]=x; siz[mid]=1;
	if(l==r) return;
	build(mid,l,mid-1); build(mid,mid+1,r);
	pushup(mid);
}

int find(int x,int k){//查询排名为k的点 
	pushdown(x); int s=siz[ch[x][0]];
	if(k==s+1) return x;
	if(k<=s) return find(ch[x][0],k);
	else return find(ch[x][1],k-s-1); 
}

inline void rever(int l,int r){//翻转 
	int x=find(root,l),y=find(root,r+2);//l-1,r+1
	splay(x,root); splay(y,ch[x][1]);
	rev[ch[y][0]]^=1;
}

int main(){
	n=rd(); m=rd(); root=(n+3)>>1; build(root,1,n+2);
	while(m--){
		int l=rd(),r=rd();
		rever(l,r);
	}
	for(int i=2;i<=n+1;i++) printf("%d ",find(root,i)-1);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值