复习一下Splay,没想到一个简单的模板写了一个多小时。。。
注:该模板比较短,所以可能会有些难以理解。该结构体包含插入与查询操作。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 100010;
struct Splay_Tree {
int fa[MAXN], ch[MAXN][2], data[MAXN], r, pn;
void clear(int x) { //初始化并将根节点赋值为x
r = pn = 1;
memset(fa, 0, sizeof(fa));
memset(ch, 0, sizeof(ch));
memset(data, 0, sizeof(data));
data[1] = x;
}
void Rotate(int p, bool t) {
int f = fa[p];
fa[ch[f][t^1] = ch[p][t]] = f;
fa[ch[fa[f]][ch[fa[f]][1]==f] = p] = fa[f];
ch[fa[f] = p][t] = f;
}
void splay(int x) {
int p;
while(fa[x]) {
p = fa[x];
if(!fa[p]) {
Rotate(x, x==ch[p][0]);
break;
}
bool f = x==ch[p][0], f1 = p==ch[fa[p]][0], f2 = p==ch[fa[p]][1];
Rotate(f?f1?p:x:f2?p:x, f);
Rotate(x, f1);
}
r = x;
}
void insert(int x) {
int p = r;
while(true) {
if((x<data[p] && !ch[p][0]) || (x>=data[p] && !ch[p][1])) {
fa[++pn] = p;
ch[p][x>=data[p]] = pn;
data[pn] = x;
break;
}
p = ch[p][x>=data[p]];
}
splay(pn);
}
void find(int x) {
int p = r;
while(data[p] != x) p = ch[p][x>data[p]];
splay(p);
}
};