指针运用不熟练。。。
删除操作为彻底实现。。。
具体学习后另写。。。
#include<iostream>
#include<cstdio>
using namespace std;
struct AVL
{
int num,size,h;
AVL *ch[2];
AVL(int x)
{
num=x,size=1,h=1;
ch[0]=ch[1]=NULL;
}
int cmp(int x)const
{
if(num==x)return -1;
return num>x ? 0:1;
}
void up() //must use '->'
{
size=1,h=1;
int tmp=0;
if(ch[0]!=NULL) size+=ch[0]->size,tmp=max(tmp,ch[0]->h);
if(ch[1]!=NULL) size+=ch[1]->size,tmp=max(tmp,ch[1]->h);
h+=tmp;
}
};
AVL* root=NULL;
inline int height(AVL* x)
{
if(x==NULL)return 0;
return x->h;
}
inline void rotate(AVL* &x,int d) //must use '->'
{
AVL *tmp=x->ch[d^1];
x->ch[d^1]=tmp->ch[d];
tmp->ch[d]=x;
x->up();
tmp->up();
x=tmp;
}
inline void adjust(AVL* &x,int d)
{
if((height(x->ch[d])-height(x->ch[d^1]))==2)
{
if(height(x->ch[d]->ch[d])<height(x->ch[d]->ch[d^1]))
rotate(x->ch[d],d);
rotate(x,d^1);
}
}
void insert(AVL* &x,int num)
{
if(x==NULL)x=new AVL(num);
else
{
int d=x->cmp(num);
if(d!=-1)
{
insert(x->ch[d],num);
adjust(x,d);
}
}
x->up();
}
void del(AVL* &x,int num)
{
int d=x->cmp(num);
if(d!=-1)
del(x->ch[d],num);
else
{
if(x->ch[0]!=NULL)
{
AVL* tmp=NULL;
for(tmp=x->ch[0];tmp!=NULL;tmp=tmp=tmp->ch[0]){};
x->num=tmp->num;
del(x->ch[0],tmp->num);
}
else if(x->ch[1]!=NULL)
{
AVL* tmp=NULL;
for(tmp=x->ch[1];tmp!=NULL;tmp=tmp->ch[1]){}
x->num=tmp->num;
del(x->ch[1],tmp->num);
}
else x=NULL;
if(x!=NULL)
{
if(height(x->ch[d])>height(x->ch[d^1]))
adjust(x,d^1);
else adjust(x,d);
}
}
if(x!=NULL)x->up();
}
///
void print(AVL* x)
{
if(x!=NULL)
{
printf(" %d %d %d \n",x->num,x->h,x->size);
print(x->ch[0]);
print(x->ch[1]);
}
}
int main()
{
int n;
int use[20];
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&use[i]);
for(int i=1;i<=n;i++)
insert(root,use[i]);
int tmp=0;
while(cin>>tmp)
{
del(root,tmp);
print(root);
}
print(root);
while(1);
return 0;
}