洛谷P2596 [ZJOI2006]书架
指针写的代码量真心大
Code:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=900000;
int key[maxn];
int D[maxn];
char A[30];
int n,m;
struct Node{
Node *ch[2];
int v,s,val;
Node(int a,int b){//val:编号,v:优先级.
val=a,v=b,s=1;
ch[0]=ch[1]=NULL;
}
int cmp1(int x){
if(x<v)return 0;if(x==v)return -1;return 1;
}
int ls(){
if(ch[0]==NULL)return 0;return ch[0]->s;
}
int cmp2(int x){ //比较大小
int lsize=ch[0]==NULL?0:ch[0]->s;
if(x<=lsize)return 0;
if(x==lsize+1)return -1;
return 1;
}
void maintain(){
s=1;
if(ch[0]!=NULL)s+=ch[0]->s;
if(ch[1]!=NULL)s+=ch[1]->s;
}
};
void rotate(Node* &o,int d){
Node *k=o->ch[d^1];o->ch[d^1]=k->ch[d];k->ch[d]=o;
o->maintain();k->maintain();o=k;
}
void splay1(Node* &o,int k){ //第k大
int d=o->cmp2(k);
if(d==1)k-=o->ls()+1;
if(d!=-1){
Node *p=o->ch[d];
int d2=p->cmp2(k);
if(d2==1)k-=p->ls()+1;
if(d2!=-1){
splay1(p->ch[d2],k);
if(d==d2)rotate(o,d^1);
else rotate(o->ch[d],d2^1);
}
rotate(o,d^1);
}
}
void splay2(Node* &o,int x){
int d=o->cmp1(x);
if(d!=-1){
Node *p=o->ch[d];
int d2=p->cmp1(x);
if(d2!=-1){
splay2(p->ch[d2],x);
if(d==d2)rotate(o,d^1);
else rotate(o->ch[d],d2^1);
}
rotate(o,d^1);
}
}
void build(int arr[],int l,int r,Node* &o){
if(l>r)return;
int mid=(l+r)/2;
o=new Node(arr[mid],mid);
build(arr,l,mid-1,o->ch[0]);
build(arr,mid+1,r,o->ch[1]);
o->maintain();
}
Node *head;
void init(){
head=NULL;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i){
int a;scanf("%d",&a);
key[a]=i,D[i]=a;
}
build(D,1,n,head);
}
void remove(Node* &o){
if(o->ch[0]==NULL)o=o->ch[1];
else if(o->ch[1]==NULL)o=o->ch[0];
else{
splay1(o->ch[0],o->ch[0]->s);
Node *left=o->ch[0];
Node *right=o->ch[1];
left->ch[1]=right;
left->maintain();
o=left;
}
}
int main(){
// freopen("in.txt","r",stdin);
init();
int maxv=n+1,minv=0;
for(int i=1;i<=m;++i){
int S;
scanf("%s",A);scanf("%d",&S);
if(A[0]=='T'){
splay2(head,key[S]);
remove(head);
splay1(head,1);
head->ch[0]=new Node(S,--minv);
key[S]=minv;
head->maintain();
}
if(A[0]=='B'){
splay2(head,key[S]);
remove(head);
splay1(head,head->s);
head->ch[1]=new Node(S,++maxv);
key[S]=maxv;
head->maintain();
}
if(A[0]=='I'){
int t;
scanf("%d",&t);
if(t!=0){
splay2(head,key[S]);
if(t==-1){
splay1(head->ch[0],head->ch[0]->s);
swap(key[S],key[head->ch[0]->val]);
swap(head->val,head->ch[0]->val);
}
else if(t==1){
splay1(head->ch[1],1);
swap(key[S],key[head->ch[1]->val]);
swap(head->val,head->ch[1]->val);
}
}
}
if(A[0]=='A'){
splay2(head,key[S]);
printf("%d\n",head->ls());
}
if(A[0]=='Q'){
splay1(head,S);
printf("%d\n",head->val);
}
}
return 0;
}