【玄关】带旋Treap不开O2MLE,开O2TLE
查看原帖
【玄关】带旋Treap不开O2MLE,开O2TLE
999274
CNS_5t0_0r2楼主2023/12/21 13:22
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int N = 1e5 + 9;
int q,op,x,cnt = 1,root = 1;
struct node{
	int l,r,val,num_val,tree_size,num_cnt;
	node(int _num_val_){
		l = 0;
		r = 0;
		val = rand();
		num_val = _num_val_;
		tree_size = 1;
		num_cnt = 1;
	}
	node(){}
} a[N];
void push_up(int root){
	a[root].tree_size = a[a[root].l].tree_size + a[a[root].r].tree_size + a[root].num_cnt;
}
int x_rank(int x,int root){
	if(root){
		if(x < a[root].num_val)
			return x_rank(x,a[root].l);
		else if(x > a[root].num_val)
			return x_rank(x,a[root].r) + a[a[root].l].tree_size + a[root].num_cnt;
		return a[a[root].l].tree_size + 1;
	}
	return 1;
}
int xth_num(int x,int root){
	if(x <= a[a[root].l].tree_size)
		return xth_num(x,a[root].l);
	else if(x <= a[a[root].l].tree_size + a[root].num_cnt)
		return a[root].num_val;
	return xth_num(x - (a[a[root].l].tree_size + a[root].num_cnt),a[root].r);
}
void zig(int &root){
	int u = a[root].l;
	a[root].l = a[u].r;a[u].r = root;root = u;
	push_up(a[root].r);push_up(root);
}
void zag(int &root){
	int u = a[root].r;
	a[root].r = a[u].l;a[u].l = root;root = u;
	push_up(a[root].l);push_up(root);
}
void insert(int x,int &root){
	if(x < a[root].num_val){
		if(!a[root].l){
			a[root].l = ++cnt;
			a[cnt] = node(x);
		}
		else{
			insert(x,a[root].l);
			if(a[root].val < a[a[root].l].val)
				zig(root);
		}
	}
	else if(x > a[root].num_val){
		if(!a[root].r){
			a[root].r = ++cnt;
			a[cnt] = node(x);
		}
		else{
			insert(x,a[root].r);
			if(a[root].val < a[a[root].r].val)
				zag(root);
		}
	}
	else{
		a[root].num_cnt++;
	}
	push_up(root);
}
void Remove(int x,int &root){
	if(!root)
		return;
	if(x == a[root].num_val){
		if(a[root].num_cnt >= 2){
			a[root].num_cnt--;
			return;
		}
		if(a[root].l || a[root].r){
			if(!a[root].r || a[a[root].l].val > a[a[root].r].val){
				zig(root);
				Remove(x,a[root].r);
			}
			else{
				zag(root);
				Remove(x,a[root].l);
			}
			push_up(root);
		}
		else
			root = 0;
		return;
	}
	if(x < a[root].num_val)
		Remove(x,a[root].l);
	else
		Remove(x,a[root].r);
	push_up(root);
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	srand(time(0));
	cin >> q;
	for(int i = 1;i <= q;i++){
		cin >> op >> x;
		if(op == 1)
			insert(x,root);
		if(op == 2)
			Remove(x,root);
		if(op == 3)
			cout << x_rank(x,root) << '\n';
		if(op == 4)
			cout << xth_num(x,root) << '\n';
		if(op == 5)
			cout << xth_num(x_rank(x,root) - 1,root) << '\n';
		if(op == 6)
			cout << xth_num(x_rank(x + 1,root),root) << '\n';

	}
	return 0;
}
2023/12/21 13:22
加载中...