萌新刚学oi,求助splay
查看原帖
萌新刚学oi,求助splay
482728
Engulf楼主2022/3/20 11:43

splay TLE 60pts /kk

#include <bits/stdc++.h>
using namespace std;

inline int read(){
	int x=0,f=0;char ch=getchar();
	while(!isdigit(ch))f^=!(ch^45),ch=getchar();
	while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
	return f?-x:x;
}
inline void write(int x){
	if(x<0)x=-x,putchar('-');
	if(x>=10)write(x/10);
	putchar(x%10+'0');
}
inline void writeln(int x){write(x);puts("");}

int n,idx,root;
struct node{
	int son[2],fa,siz,val,cnt;
}tr[100005];
void pushup(int p){tr[p].siz=tr[tr[p].son[0]].siz+tr[tr[p].son[1]].siz+tr[p].cnt;}
void rotate(int x){
	int y=tr[x].fa,z=tr[y].fa;
	int k=tr[y].son[1]==x;
	tr[z].son[tr[z].son[1]==y]=x,tr[x].fa=z;
	tr[y].son[k]=tr[x].son[k^1],tr[tr[x].son[k^1]].fa=y;
	tr[x].son[k^1]=y,tr[y].fa=x;
	pushup(y);pushup(x);
}
void splay(int x,int goal){
	while(tr[x].fa!=goal){
		int y=tr[x].fa,z=tr[y].fa;
		if(z!=goal){
			if(tr[y].son[1]==x ^ tr[z].son[1]==y)rotate(x);
			else rotate(y);
		}
		rotate(x);
	}
	if(!goal)root=x;
}
void insert(int val){
	int p=root,fa=0;
	while(p&&tr[p].val!=val){
		fa=p;
		p=tr[p].son[val>tr[p].val];
	}
	if(p){tr[p].cnt++;}
	else{
		p=++idx;
		tr[p].cnt=tr[p].siz=1;
		tr[p].val=val;
		if(fa)tr[fa].son[val>tr[fa].val]=p;
		tr[p].fa=fa;
	}
	splay(p,0);
}
void find(int val){
	int p=root;
	while(tr[p].son[val>tr[p].val]&&tr[p].val!=val){
		p=tr[p].son[val>tr[p].val];
	}
	splay(p,0);
}
int kth(int k){
	int p=root;
	while(1){
		if(tr[tr[p].son[0]].siz>=k)p=tr[p].son[0];
		else if(tr[tr[p].son[0]].siz+tr[p].cnt==k)return p;
		else k-=tr[tr[p].son[0]].siz+tr[p].cnt,p=tr[p].son[1];
	}
}
int pre(int val){
	find(val);
	if(tr[root].val<val)return root;
	int p=tr[root].son[0];
	while(tr[p].son[1])p=tr[p].son[1];
	return p;
}
int nxt(int val){
	find(val);
	if(tr[root].val>val)return root;
	int p=tr[root].son[1];
	while(tr[p].son[0])p=tr[p].son[0];
	return p;
}
void remove(int val){
	int x=pre(val),y=nxt(val);
	splay(x,0);splay(y,x);
	if(tr[tr[y].son[0]].cnt>1)tr[tr[y].son[0]].cnt--,splay(tr[y].son[0],0);
	else{
		tr[y].son[0]=0;
		pushup(y);pushup(x);
	}
}

int main(){
	n=read();
	insert(1e9);insert(-1e9);
	while(n--){
		int op=read(),x=read();
		switch(op){
			case 1:insert(x);break;
			case 2:remove(x);break;
			case 3:
				find(x);
				writeln(tr[tr[root].son[0]].siz);
				break;
			case 4:
				writeln(tr[kth(x+1)].val);
				break;
			case 5:writeln(tr[pre(x)].val);break;
			case 6:writeln(tr[nxt(x)].val);break;
		}
	}
	return 0;
}
2022/3/20 11:43
加载中...