[BZOJ1507]NOI2003 Editor|splay

Splay/块状链表裸题。。不过范围有点大,具体操作像维护数列样搞就是,输出的时候中序遍历一下那个区间的子树。。要注意的是读入的时候,最快的方法还是一个一个getchar,还有一个坑的地方就是scanf(“\n”)的时候会把下一行开头的空格读掉。。

splay:

#include<iostream>
#include<cstdio>
#include<memory.h>
#include<cstring>
#define maxn 2100005
using namespace std;
char s[maxn],cc;
int n,i,nd=0,root=0,len,pos=0,c[maxn][2],pre[maxn],size[maxn],v[maxn];
void newnode(int &x,int fa,int val)
{
	x=++nd;pre[x]=fa;
	size[x]=1;v[x]=val;
	c[x][0]=c[x][1]=0;
}
void update(int x){size[x]=size[c[x][0]]+size[c[x][1]]+1;}
void rot(int x,int kind)
{
	int y=pre[x],z=pre[y];
	c[y][!kind]=c[x][kind];pre[c[x][kind]]=y;
	c[x][kind]=y;pre[y]=x;
	pre[x]=z;if (z) c[z][c[z][1]==y]=x;
	update(y);update(x);
}
void splay(int x,int goal)
{
	int y,z,kind;
	while (pre[x]!=goal)
	{
		y=pre[x];
		if (pre[y]==goal) rot(x,c[y][0]==x);
		else
		{
			z=pre[y];kind=c[z][0]==y;
			if (c[y][kind]==x) rot(x,!kind);else rot(y,kind);
			rot(x,kind);
		}
	}
	if (goal==0) root=x; 
}
void build(int &x,int fa,int l,int r)
{
	if (l>r) return;
	int mid=(l+r)/2;
	newnode(x,fa,s[mid]);
	if (l==r) return;
	build(c[x][0],x,l,mid-1);build(c[x][1],x,mid+1,r);
	update(x);
}
int findkth(int x,int k)
{
	if (size[c[x][0]]>=k) return findkth(c[x][0],k);
	if (size[c[x][0]]+1==k) return x;
	return findkth(c[x][1],k-size[c[x][0]]-1);
}
void ins(int pos,int len)
{
	int x=findkth(root,pos+1),y=findkth(root,pos+2);
	splay(x,0);splay(y,x);
	build(c[y][0],y,1,len);
	update(y);update(x);
}
void del(int pos,int len)
{
	int x=findkth(root,pos+1),y=findkth(root,pos+len+2);
	splay(x,0);splay(y,x);
	c[y][0]=0;
	update(y);update(x);
}
void print(int x)
{
	if (!x) return;
	print(c[x][0]);putchar(v[x]);print(c[x][1]);
}
void get(int pos,int len)
{
	int x=findkth(root,pos+1),y=findkth(root,pos+len+2);
	splay(x,0);splay(y,x);
	print(c[y][0]);printf("\n");
}
int main()
{
	freopen("1507.in","r",stdin);
	freopen("1507.out","w",stdout);
	scanf("%d\n",&n);
	newnode(root,0,0);newnode(c[root][1],root,0);update(root);size[0]=0;
	for (i=1;i<=n;i++)
	{
		scanf("%s",s+1);
		switch (s[1])
		{
			case 'M':scanf("%d\n",&pos);break;
			case 'P':pos--;break;
			case 'N':pos++;break;
			case 'G':scanf("%d\n",&len);get(pos,len);break;
			case 'D':scanf("%d\n",&len);del(pos,len);break;
			case 'I':
				scanf("%d",&len);
				for (int t=0;t<len;)
                {
                    while ((cc=getchar())==10 || cc==13);
                    s[++t]=cc;
                }
				ins(pos,len);
				break;
		}
	}
	fclose(stdin);
	fclose(stdout);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值