文艺平衡树(splay旋转操作)

您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 4 1 


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=300009;
int ch[maxn][2],fa[maxn],m,rev[maxn]={0},n,a[maxn],rt,size[maxn];
void up(int x)
{
	size[x]=size[ch[x][0]]+size[ch[x][1]]+1;
}
void down(int x)
{
	if (rev[x])
	{
		rev[ch[x][0]]^=1;
		rev[ch[x][1]]^=1;
		swap(ch[x][0],ch[x][1]);
		rev[x]=0;//注意清零!!
	}///旋转标记的下传
}
void rotate(int x)
{
	int y=fa[x],z=fa[y],l,r;
	if (ch[y][0]==x) l=0;else l=1;r=l^1;
	if (z)
	if (ch[z][0]==y) ch[z][0]=x;else ch[z][1]=x;
	fa[x]=z;fa[ch[x][r]]=y;fa[y]=x;
	ch[y][l]=ch[x][r];ch[x][r]=y;
	up(y);///up的位置
}
void splay(int x,int k)
{
	int y,z;
	while (fa[x]!=k)
	{
		y=fa[x];z=fa[y];
		if (z!=k)
		if ((ch[z][0]==y)^(ch[y][0]==x)) rotate(x);else rotate(y);
		rotate(x);
	}
	if (k==0) rt=x;
	up(x);//splay的up的两个位置
}
int build(int l,int r,int f)
{
	if (l>r) return 0;
	int mid=(l+r)>>1;
	fa[mid]=f;size[mid]=1;
	if(l==r) return mid; ///这个地方当时出错了!!!!,应该是return mid!!!
	ch[mid][0]=build(l,mid-1,mid);
	ch[mid][1]=build(mid+1,r,mid);
	up(mid);///up的位置
	return mid;
}
int find(int x,int t)
{
	down(x);//查找需用,在最初down一下
	if (size[ch[x][0]]+1==t) return x;
	if (size[ch[x][0]]>=t) return find(ch[x][0],t);
	else return find(ch[x][1],t-size[ch[x][0]]-1);
}
int main()
{
	scanf("%d%d",&n,&m);
	rt=build(1,n+2,0);

	while (m--)
	{
		int l,r;
		scanf("%d%d",&l,&r);
		int x=find(rt,l),y=find(rt,r+2);
		splay(x,0);
		splay(y,x);
		rev[ch[y][0]]^=1;
		size[0]=0;
	}
	for (int i=2;i<=n+1;i++) 
	printf("%d ",find(rt,i)-1);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值