题目来源: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;
}