玄关FHQ-treap
查看原帖
玄关FHQ-treap
735869
P_ZXY_楼主2025/1/21 10:46

rt.

#include<cstdio>
#include<iostream>
using namespace std;
const int N = 114514+1919810;

int n,opt,x,l,r,p,cnt,root;
struct node{int ls,rs,key,data,siz;}tn[N<<1];

void push_up(int num){
	tn[num].siz = tn[tn[num].ls].siz + tn[tn[num].rs].siz + 1;
	return;
}

void add_tree(int x){
	tn[++cnt].siz = 1;
	tn[cnt].ls = tn[cnt].rs = 0;
	tn[cnt].data = x;tn[cnt].key = rand();
}

void split(int num,int x,int &l,int &r){
	if(!num){l = r = 0;return;}
	if(tn[num].data <= x){
		l = num;split(tn[num].rs,x,tn[num].rs,r);
	}else{
		r = num;split(tn[num].ls,x,l,tn[num].ls);
	}
	push_up(num);
}

int merge(int l,int r){
	if(!l || !r) return l+r;
	if(tn[l].key <= tn[r].key){
		tn[l].rs = merge(tn[l].rs,r);
		push_up(l);return l;
	}else{
		tn[r].ls = merge(l,tn[r].ls);
		push_up(r);return r;
	}
}

void add_node_x(int x){
	split(root,x,l,r);
	add_tree(x);
	root = merge(merge(l,cnt),r);
}

void delete_node_x(int x){
	split(root,x,l,r);
	split(l,x-1,l,p);
	p = merge(tn[p].ls,tn[p].rs);
	root = merge(merge(l,p),r);
}

int find_x_number(int x){
	split(root,x-1,l,r);
	int ans = tn[l].siz + 1;
	root = merge(l,r);
	return ans;
}

int number_x(int u,int x){
	int ans;
	if(x <= tn[tn[u].ls].siz) ans = number_x(tn[u].ls,x);
	else if(x == tn[tn[u].ls].siz+1) ans = u;
	else{
		x -= (tn[tn[u].ls].siz+1);
		ans = number_x(tn[u].rs,x);
	}
	return tn[ans].data;
}

int x_front(int x){
	split(root,x-1,l,r);
	int ans = tn[number_x(l,tn[l].siz)].data;
	root = merge(l,r);
	return ans;
}

int x_back(int x){
	split(root,x,l,r);
	int ans = tn[number_x(r,1)].data;
	root = merge(l,r);
	return ans;
}

int main(){
	ios::sync_with_stdio(0);cin.tie(0);
	cin >> n;
	while(n-- && cin >> opt >> x){
		if(opt == 1) add_node_x(x);
		else if(opt == 2) delete_node_x(x);
		else if(opt == 3) cout << find_x_number(x) << '\n';
		else if(opt == 4) cout << number_x(root,x) << '\n';
		else if(opt == 5) cout << x_front(x) << '\n';
		else cout << x_back(x) << '\n';
	}
	return 0;
}
2025/1/21 10:46
加载中...