Splay
写这玩意好累~~~~
这里贴一份用指针写的(为什么周围的神犇不喜欢用指针呢??)
#include<cstdio>
#include<iostream>
#include<cstring>
#define MAXN 100000
using namespace std;
class SplayTree{
private:
struct node
{
int key;
node *lc,*rc,*fa;
};
node *root,*tail;
node pool[MAXN];
inline void rotate(node *x)
{
node *y=x->fa;
node *z=y->fa;
node *b=x==y->lc ? x->rc : x->lc;
x->fa=z,y->fa=x;
if(b)
b->fa=y;
if(z)
( z->lc==y ? z->lc : z->rc )=x;
if(x==y->lc)
x->rc=y,y->lc=b;
else
x->lc=y,y->rc=b;
}
inline void Splay(node *x,node *target=NULL)
{
while(x->fa!=target)
{
if(x->fa->fa!=target)
{
if((x->fa->fa->lc==x->fa)==(x->fa->lc==x))
rotate(x->fa);
else
rotate(x);
}
rotate(x);
}
if(target==NULL)
root=x;
}
inline node *find(int key)
{
node *p=root;
while(p)
{
if(key>p->key)
p=p->rc;
else
if(key<p->key)
p=p->lc;
else
return p;
}
return NULL;
}
public:
SplayTree()
{
root=NULL;
tail=pool;
}
inline bool Find(const int &key)
{
node *p=find(key);
if(!p)
return false;
Splay(p);
return true;
}
inline void Insert(const int key)
{
node **q=&root;
node *p=root;
node *fp=NULL;
while(p)
{
fp=p;
if(key>p->key)
q=&p->rc,p=p->rc;
else
if(key<p->key)
q=&p->lc,p=p->lc;
else
{
Splay(p);
return ;
}
}
p = tail++;
p->key = key;
p->fa = fp, p->lc = p->rc = NULL;
*q = p;
Splay(p);
}
inline void Delete(const int key)
{
node *p=find(key);
Splay(p);
if(!p->lc&&!p->rc)
root=NULL;
else
if(!p->lc)
root->fa=NULL,root=p->rc;
else
if(!p->rc)
root->fa=NULL,root=p->lc;
else
{
node *pre=p->lc,*next=p->rc;
while(pre->rc)
pre=pre->rc;
while(next->lc)
next=next->lc;
Splay(pre);
Splay(next,pre);
next->lc=NULL;
}
}
};
这也有个Splay专辑~~~~~很有用呢(用数组写的)
http://www.cnblogs.com/proverbs/archive/2013/01/15/2860717.html