9分求助
查看原帖
9分求助
374851
lian13817981484楼主2023/2/18 12:48
#include<cstdio>
using namespace std;
int n,m,a,tot,top,rt,fa[500005],val[500005],ch[500005][2],book[500005],stk[500005];
char str[5];
int get(int x){
	return x == ch[fa[x]][1];
}
void clear(int x){
	fa[x] = val[x] = ch[x][0] = ch[x][1] = 0;
}
void rotate(int x){
	int y = fa[x],z = fa[y],chk = get(x);
	ch[y][chk] = ch[x][chk^1];
	if(ch[x][chk^1])fa[ch[x][chk^1]] = y;
	ch[x][chk^1] = y;
	fa[y] = x;
	fa[x] = z;
	if(z)ch[z][y == ch[z][1]] = x;
}
void splay(int x){
	for(int f = fa[x];f != 0;rotate(x),f = fa[x]){
		if(fa[f])rotate(get(x) == get(f) ? f : x);
	}
	rt = x;
}
void insert(int x){
	if(!rt){
		tot++;
		val[tot] = x;
		rt = tot;
		return;
	}
	int cur = rt,f = 0;
	while(true){
		if(x == val[cur]){
			splay(cur);
			return;
		}
		f = cur;
		cur = ch[cur][x > val[cur]];
		if(!cur){
			tot++;
			val[tot] = x;
			fa[tot] = f;
			ch[f][x > val[f]] = tot;
			splay(tot);
			return;
		}
	}
}
int pre(){
	int cur = ch[rt][0];
	if(!cur)return cur;
	while(ch[cur][1])cur = ch[cur][1];
	splay(cur);
	return cur;
}
int nxt(){
	int cur = ch[rt][1];
	if(!cur)return cur;
	while(ch[cur][0])cur = ch[cur][0];
	splay(cur);
	return cur;
}
void find(int x){
	int cur = rt;
	while(true){
		if(val[cur] == x){
			splay(cur);
			return;
		}
		if(x > val[cur]){
			cur = ch[cur][1];
		}
		if(x < val[cur]){
			cur = ch[cur][0];
		}
	}
}
void del(int x){
	find(x);
	if(!ch[rt][0] && !ch[rt][1]){
		clear(rt);
		rt = 0;
		return;
	}
	if(!ch[rt][0]){
		int cur = rt;
		rt = ch[rt][1];
		fa[rt] = 0;
		clear(cur);
		return;
	}
	if(!ch[rt][1]){
		int cur = rt;
		rt = ch[cur][0];
		fa[rt] = 0;
		clear(cur);
		return;
	}
	int cur = rt,p = pre();
	ch[p][1] = ch[cur][1];
	fa[ch[cur][1]] = p;
	clear(cur);
	return;
}
int main(){
	scanf("%d %d",&n,&m);
	for(int i = 1;i <= m;i++){
		scanf("%s",str);
		if(str[0] == 'D'){
			scanf("%d",&a);
			insert(a);
			book[a] = 1;
			stk[++top] = a;
		}
		else if(str[0] == 'Q'){
			scanf("%d",&a);
			if(book[a] == 1){
				printf("0\n");
				continue;
			}
			insert(a);
			int p = val[pre()];
			del(a);
			insert(a);
			int nx = val[nxt()];
			del(a);
			printf("%d\n",nx-p-1);
		}
		else{
			a = stk[top--];
			book[a] = 0;
			del(a);
		}
	}
	return 0;
}
2023/2/18 12:48
加载中...