題目來源:http://www.lydsy.com/JudgeOnline/problem.php?id=1861
這題是splay維護區間。
既然是維護區間,那麼存在splay裏的值就不一定要滿足二叉排序樹的”左<中<右”的性質,此時要維護某個值在序列裏的位置,可以維護一個pos數組,代表某個值在splay中的位置,把這個結點轉到根,輸出左子樹的大小即爲它在序列中前面書的數量。
insert好說,找到x的前驅或後繼,swap其在splay中的數值和pos即可。
但是這題最大的鯁應該是在top和bottom(至少在我看來是這樣)。一開始我是用找到第K大轉到根再連邊的方式,但這樣對於個別點會莫名超時。正確做法是把那個點先erase掉,再調整erase掉的點左兒子或右兒子爲之前的root即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=81000;
int n,m,val=0;
int pos[N],ins[N];
int ch[N][2],f[N],s[N],cnt=0,root=0;
int a[N];
char str[30];
void pushup (int x) {
s[x]=s[ch[x][0]]+s[ch[x][1]]+1;
}
int build (int l,int r,int fa) {
if (l>r) return 0;
int x=++cnt,mid=(l+r)>>1;
f[x]=fa;
a[x]=ins[mid];
pos[ins[mid]]=x;
ch[x][0]=build(l,mid-1,x);
//pos[ins[val]]=x;a[x]=ins[val++];
ch[x][1]=build(mid+1,r,x);
pushup(x);//
return x;
}
void rotate (int x) {
int y=f[x],opt;
if (ch[f[x]][0]==x) opt=0;
else opt=1;
ch[y][opt]=ch[x][!opt];
if (ch[x][!opt]) f[ch[x][!opt]]=y;
f[x]=f[y];
if (root==y) root=x;
else if (ch[f[y]][0]==y) ch[f[y]][0]=x;
else ch[f[y]][1]=x;
f[y]=x,ch[x][!opt]=y;
pushup(y),pushup(x);
}
void splay (int x,int to=0) {
while (f[x]!=to) {
if (f[f[x]]==to) rotate(x);
else if ((ch[f[f[x]]][0]==f[x])
==(ch[f[x]][0]==x))
rotate(f[x]),rotate(x);
else rotate(x),rotate(x);
}
}
int findkth (int k,int opt=0) {
int x=root;
while (x) {
if (k==s[ch[x][0]]+1)
{if (opt) return x; else return a[x];}
else if (k<s[ch[x][0]]+1) x=ch[x][0];
else k-=s[ch[x][0]]+1,x=ch[x][1];
}
return 0;
}
int ask (int k) {
int x=pos[k];
splay(x);
return s[ch[x][0]];
}
void change (int x,int y) {
//swap(pos[a[x]],pos[a[y]]);
swap(a[x],a[y]);
pos[a[x]]=x;pos[a[y]]=y;
}
void tp (int t,int x) {
splay(x);
if (ch[x][1]>0) {
int p=ch[x][1];
while (ch[p][0]) p=ch[p][0];
splay(p,x);
ch[p][0]=ch[x][0];
f[ch[p][0]]=p;
pushup(p);
root=p;
}
else {
f[ch[x][0]]=0;
root=ch[x][0];
}
f[x]=ch[x][0]=ch[x][1]=0;
f[root]=x;
ch[x][t]=0;
ch[x][!t]=root;
pushup(x);
root=x;
splay(x);
}
void move (int k,int opt) {
int x,p;
if (opt==0) return ;
if (opt==-1) {
x=pos[k];
splay(x);
p=ch[x][0];
if (!ch[x][0]) return ;
while (ch[p][1]) p=ch[p][1];
if (p) {
change(p,x);
}
}
if (opt==1) {
x=pos[k];
splay(x);
p=ch[x][1];
if (!ch[x][1]) return ;
while (ch[p][0]) p=ch[p][0];
if (p) {
change(p,x);
}
}
}
int main () {
int x,opt;
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&ins[i]);
root=build(1,n,0);
for (int i=1;i<=m;i++) {
scanf("%s",str);
if (str[0]=='Q') {
scanf("%d",&x);
printf("%d\n",findkth(x));
}
else if (str[0]=='A') {
scanf("%d",&x);
printf("%d\n",ask(x));
}
else if (str[0]=='T') {
scanf("%d",&x);
tp(0,pos[x]);
}
else if (str[0]=='B') {
scanf("%d",&x);
tp(1,pos[x]);
}
else if (str[0]=='I') {
scanf("%d%d",&x,&opt);
move(x,opt);
}
}
return 0;
}