您的位置:首页 > 其它

[BZOJ1507][NOI2003]Editor

2015-07-18 23:23 435 查看
原题地址

Splay练手题.

AC code:

#include <cstdio>
#include <cstdlib>
#include <cstring>
const int N=3000010;
int n,pos;
char text
;

struct Snode
{
char ch;
bool tag;
int num,tot;
Snode *Prev,*Ch[2];
};

struct Splay
{
Snode *NIL,*root,*pool;

Splay(int size)
{
pool=(Snode*)malloc(size*sizeof(Snode));
NIL=root=pool++;
NIL->tot=0;
NIL->Ch[0]=NIL->Ch[1]=NULL;
insert(0,0);
insert(1,0);
}

void rotate(Snode *x,bool type){
Snode *y=x->Prev,*z=y->Prev,*b=x->Ch[type^1];
b->Prev=y;
y->Prev=x;
x->Prev=z;
y->Ch[type]=b;
x->Ch[type^1]=y;
if(z->Ch[0]==y) z->Ch[0]=x;
if(z->Ch[1]==y) z->Ch[1]=x;
x->tot=y->tot;
y->tot=y->Ch[0]->tot+y->Ch[1]->tot+1;
}

void splay(Snode *x,Snode *obj)
{
while(x->Prev!=obj){
Snode *y=x->Prev,*z=y->Prev;
if(z==obj){
if(y->Ch[0]==x) rotate(x,0);
else rotate(x,1);
}
else{
if(z->Ch[0]==y&&y->Ch[0]==x){
rotate(y,0);
rotate(x,0);
}
else if(z->Ch[1]==y&&y->Ch[1]==x){
rotate(y,1);
rotate(x,1);
}
else if(z->Ch[1]==y){
rotate(x,0);
rotate(x,1);
}
else{
rotate(x,1);
rotate(x,0);
}
}
}
if(obj==NIL) root=x;
}

void update(Snode *p)
{
if(!p->tag||p==NIL||p==root) return ;
if(p->Prev->Ch[0]==p) p->num=p->Prev->num-p->Ch[1]->tot-1;
else p->num=p->Prev->num+p->Ch[0]->tot+1;
p->tag=0;
p->Ch[0]->tag=p->Ch[1]->tag=1;
}

void insert(int key,char c)
{
_insert(&root,key,c,NIL);
}

Snode *get(int key)
{
return _get(root,key);
}

void _insert(Snode **p,int key,char c,Snode *last)
{
while(1){
if(*p==NIL){
*p=pool++;
(*p)->ch=c;
(*p)->tag=0;
(*p)->tot=1;
(*p)->num=key;
(*p)->Prev=last;
(*p)->Ch[0]=(*p)->Ch[1]=NIL;
splay(*p,NIL);
return ;
}
update(*p);
last=*p;
(*p)->tot++;
bool flag=key>(*p)->num;
p=&(*p)->Ch[flag];
}
}

Snode* _get(Snode *p,int key)
{
update(p);
if(key==p->num) return p;
bool flag=key>p->num;
return _get(p->Ch[flag],key);
}

void LDR(Snode *p)
{
update(p);
if(p->Ch[0]!=NIL) LDR(p->Ch[0]);
printf("%c",p->ch);
if(p->Ch[1]!=NIL) LDR(p->Ch[1]);
}
};

int main()
{
scanf("%d",&n);
Splay T(N);
for(int i=1;i<=n;i++){
int k;
char s[11];
scanf("%s",s);
if(!strcmp(s,"Prev")) pos--;
else if(!strcmp(s,"Next")) pos++;
else{
scanf("%d",&k);
if(!strcmp(s,"Move")) pos=k;
else if(!strcmp(s,"Get")){
T.splay(T.get(pos),T.NIL);
T.splay(T.get(pos+k+1),T.root);
T.LDR(T.root->Ch[1]->Ch[0]);
printf("\n");
}
else if(!strcmp(s,"Delete")){
Snode *L=T.get(pos),*R=T.get(pos+k+1);
T.splay(L,T.NIL);
T.splay(R,T.root);
R->tag=1;
R->Ch[0]=T.NIL;
R->tot=R->Ch[1]->tot+1;
L->tot=L->Ch[0]->tot+L->Ch[1]->tot+1;
}
else{
for(int j=1;j<=k;j++){
scanf("%c",&text[j]);
if(text[j]=='\n') j--;
}
for(int j=1;j<=k;j++){
T.splay(T.get(pos+j),T.NIL);
T.splay(T.get(pos+j-1),T.root);
T.insert(pos+j,text[j]);
T.root->Ch[1]->tag=1;
}
}
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: