求助!FHQ_TREAP错了!悬关
查看原帖
求助!FHQ_TREAP错了!悬关
806330
LinkCatTree楼主2023/8/6 16:10
#include <bits/stdc++.h>
using namespace std;

int n;
mt19937 rng(1234567);
const int MS=100005;
struct Node {
	int lsn,rsn;
	int key,pri,siz;
};
int tSize=0,root=0;
Node treap[MS];
void makeNewNode(int x) {
	++tSize;
	treap[tSize].siz=1;
	treap[tSize].lsn=treap[tSize].rsn=0;
	treap[tSize].key=x,treap[tSize].pri=(int)(rng()>>1);
	return ;
}
void updateRoot(int u) {
	treap[u].siz=treap[treap[u].lsn].siz+treap[treap[u].rsn].siz+1;
	return ;
}
void split(int u,int x,int &L,int &R) {
	if(u==0) {
		L=R=0;
		return ;
	}
	if(treap[u].key<=x) L=u,split(treap[u].rsn,x,treap[u].rsn,R);
	else R=u,split(treap[u].lsn,x,L,treap[u].lsn);
	updateRoot(u);
	return ;
}
int merge(int L,int R) {
	if(L==0||R==0) return L+R;
	if(treap[L].pri>treap[R].pri) {
		treap[L].rsn=merge(treap[L].rsn,R);
		updateRoot(L);
		return L;
	}
	else {
		treap[R].lsn=merge(L,treap[R].lsn);
		updateRoot(R);
		return R;
	}
}
int insert(int x) {
	int L,R;
	split(root,x,L,R);
	makeNewNode(x);
	root=merge(merge(L,tSize),R);
	return tSize;
}
int delNum(int x) {
	int L,M,R;
	split(root,x,L,R);
	split(root,x-1,L,M);
	M=merge(treap[M].lsn,treap[M].rsn);
	root=merge(merge(L,M),R);
	return root;
}
int getRank(int x) {
	int L,R,res;
	split(root,x-1,L,R);
	res=treap[L].siz+1;
	root=merge(L,R);
	return res;
}
int kth(int u,int k) {
	if(k==treap[treap[u].lsn].siz+1) return u;
	if(k<=treap[treap[u].lsn].siz) return kth(treap[u].lsn,k);
	return kth(treap[u].rsn,k-treap[treap[u].lsn].siz-1);
}
int precursor(int x) {
	int L,R,res;
	split(root,x-1,L,R);
	res=treap[kth(L,treap[L].siz)].key;
	root=merge(L,R);
	return res;
}
int successor(int x) {
	int L,R,res;
	split(root,x,L,R);
	res=treap[kth(R,1)].key;
	root=merge(L,R);
	return res;
}

int main() {
	scanf("%d",&n);
	while(n--) {
		int opt,x;
		scanf("%d%d",&opt,&x);
		if(opt==1) insert(x);
		if(opt==2) delNum(x);
		if(opt==3) printf("%d\n",getRank(x));
		if(opt==4) printf("%d\n",treap[kth(root,x)].key);
		if(opt==5) printf("%d\n",precursor(x));
		if(opt==6) printf("%d\n",successor(x));
	}
	return 0;
}

提交记录

2023/8/6 16:10
加载中...