被hack的Splay求条 100pts but WA
查看原帖
被hack的Splay求条 100pts but WA
901471
five_rice_water楼主2024/12/7 00:05
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+5;
const int Inf = 1e9+5;
int n,m,root,tot;
struct node{
	int ch[2],siz,cnt,val,fa;
}tree[N];
int get(int x){
	return x == tree[tree[x].fa].ch[1];
}
void pushup(int x){
	if(x==0){
		return;
	}
	tree[x].siz=tree[tree[x].ch[0]].siz+tree[tree[x].ch[1]].siz+tree[x].cnt; 
}
void rotate(int x){
	int y = tree[x].fa,z=tree[y].fa;
	int chk = get(x);
	tree[y].ch[chk]=tree[x].ch[chk^1];
	if(tree[x].ch[chk^1]) tree[tree[x].ch[chk^1]].fa=y;
	tree[x].ch[chk^1] = y;
	tree[y].fa = x;
	if(z){
		tree[z].ch[y==tree[z].ch[1]] = x;
	}
	tree[x].fa=z;
	pushup(y);
	pushup(x);
}
void splay(int x,int k){
	while(tree[x].fa!=k){
		int y = tree[x].fa,z = tree[y].fa;
		if(z!=k){
			if(get(x)==get(y)) {
				rotate(y);
			}		
			else{
				rotate(x);
			}
		}
		rotate(x);
	}
	if(k==0) root=x;
}
void insert(int x){
	int cur = root;
	int fa = 0;
	while(cur){
		if(x==tree[cur].val){
			tree[cur].cnt++;
			pushup(cur);
			pushup(fa);
			splay(cur,0);
			return;
		}
		fa=cur;
		cur = tree[cur].ch[x>tree[cur].val];
	}
	cur=++tot;
	tree[cur].val=x;
	tree[cur].cnt=1;
	tree[cur].fa=fa;
	tree[fa].ch[x>tree[fa].val] = cur;
	pushup(cur);
	pushup(fa);
	splay(cur,0);
}
int rnk(int x){
	int cur = root;
	int res = 0;
	while(cur){
		if(x<tree[cur].val) cur = tree[cur].ch[0];
		else {
			res+=tree[tree[cur].ch[0]].siz;
			if(tree[cur].val==x){
				splay(cur,0);
				return res+1;
			}
			res+=tree[cur].cnt;
			cur = tree[cur].ch[1];
		}
	}
	return res+1;
}
int kth(int x){
	int cur = root;
	while(cur){
		if(x<=tree[tree[cur].ch[0]].siz) cur = tree[cur].ch[0];
		else{
			x-=tree[tree[cur].ch[0]].siz;
			if(x<=tree[cur].cnt){
				splay(cur,0);
				return cur;
			}
			else{
				x-=tree[cur].cnt;
				cur = tree[cur].ch[1];
			}
		}
	}
	return -1;
}
int pre(int x){
	int cur= root;
	int ans = -2147483648;
	while(cur){
		if(tree[cur].val<x){
			ans=max(ans,tree[cur].val);
			cur=tree[cur].ch[1];
		}
		else{
			cur=tree[cur].ch[0];
		}
	}
	return ans; 
}
int nxt(int x){
	int cur = root;
	int ans = 2147483647;
	while(cur){
		if(tree[cur].val>x){
			ans = min(ans,tree[cur].val);
			cur = tree[cur].ch[0];
		}
		else{
			cur = tree[cur].ch[1];
		}
	}
	return ans;
}
int main(){
	cin>>n;
	insert(2147483647);
	insert(-2147483648);
	while(n--){
		int pos,x;
		cin>>pos>>x;
		if(pos==1){
			cout<<rnk(x)-1<<endl;
		}
		if(pos==2){
			cout<<tree[kth(x+1)].val<<endl;
		}
		if(pos==3){
			cout<<pre(x)<<endl;
		}
		if(pos==4){
			cout<<nxt(x)<<endl;
		}
		if(pos==5){
			insert(x);
		}
	}
	return 0;
}
2024/12/7 00:05
加载中...