旋转 Treap AC+WA+TLE 21pts 求调悬关
查看原帖
旋转 Treap AC+WA+TLE 21pts 求调悬关
1126325
Indestructible楼主2024/9/5 20:35

rt.

#include<bits/stdc++.h>
using namespace std;
inline void read(int& x){
	int sign=1; x=0;
	char s=getchar();
	while (s<'0'||s>'9'){
		sign=s=='-'?-1:1;
		s=getchar();
	}
	while (s>='0'&&s<='9'){
		x=x*10+s-'0';
		s=getchar();
	}
	x*=sign;
}
const int N=100005;
int cnt,root,n,opt,tp;
struct Treap{
	int ls,rs;   // 左右儿子 
	int key,pri; // 键值和优先级 
	int size;    // 子树大小 
	Treap(){}    // 初始化 
	Treap(int x): ls(0),rs(0),size(1),key(x),pri(rand()) {}
};
Treap t[N];
void rotate(int &u,int d){ // d=1 左旋,d=0 右旋 
	int tmp;
	if (d){
		tmp=t[u].rs;
		t[u].rs=t[tmp].rs;
		t[tmp].ls=u;
	}
	else{
		tmp=t[u].ls;
		t[u].ls=t[tmp].rs;
		t[tmp].rs=u;
	}
	t[tmp].size=t[u].size;
	t[u].size=t[t[u].ls].size+t[t[u].rs].size+1;
	u=tmp;
}
void Insert(int &u,int x){
	if (!u){ t[++cnt]=Treap(x); u=cnt; return; }
	t[u].size++;
	if (x>=t[u].key) Insert(t[u].rs,x);
	else Insert(t[u].ls,x);
	if (t[u].ls && t[u].pri>t[t[u].ls].pri) rotate(u,0);
	if (t[u].rs && t[u].pri>t[t[u].rs].pri) rotate(u,1);
	t[u].size=t[t[u].ls].size+t[t[u].rs].size+1;
}
void Del(int &u,int x){
	t[u].size--;
	if (t[u].key==x){
		if (t[u].ls==0 && t[u].rs==0){ u=0; return; }
		if (t[u].ls==0 || t[u].rs==0){ u=t[u].ls+t[u].rs; return; }
		// 左孩子优先级大,左旋 u,递归左孩子。右同。
		if (t[t[u].ls].pri>=t[t[u].rs].pri){ rotate(u,1); Del(t[u].ls,x); return; } 
		rotate(u,0); Del(t[u].rs,x); return;
	}
	if (t[u].key>x) Del(t[u].ls,x);
	else Del(t[u].rs,x);
}
int Rank(int u,int x){
	if (u==0) return 0;
	if (x>t[u].key) return t[t[u].ls].size+1+Rank(t[u].rs,x);
	return Rank(t[u].ls,x);
}
int kth(int u,int x){
	if (x==t[t[u].ls].size+1) return t[u].key;
	if (x<t[t[u].ls].size+1) return kth(t[u].ls,x);
	return kth(t[u].rs,x-t[t[u].ls].size-1);
}
int Precursor(int u,int x){
	return kth(root,Rank(root,x));
}
int Successor(int u,int x){
	return kth(root,Rank(root,x)+2);
}
signed main(){
	srand(time(0));
	read(n);
	while (n--){
		read(opt),read(tp);
		switch (opt){
			case 1: Insert(root,tp);                   break;
			case 2: Del(root,tp);                      break;
			case 3: printf("%d\n",Rank(root,tp)+1);    break;
			case 4: printf("%d\n",kth(root,tp));       break;
			case 5: printf("%d\n",Precursor(root,tp)); break;
			case 6: printf("%d\n",Successor(root,tp)); break;
		}
	}
	return 0;
}
2024/9/5 20:35
加载中...