93分求调
查看原帖
93分求调
1399235
Maikecheng楼主2025/7/22 18:58
#include<bits/stdc++.h>
using namespace std;
const long long N=1e5+5;
const double alpha=0.75;
struct Node{
	int ls,rs;
	int val;
	int tot;
	int sz;
	int del;
}t[N];
int order[N],cnt;
int tree_stak[N],top=0;
int root=0;
void inorder(int u){
	if(!u)return;
	inorder(t[u].ls);
	if(t[u].del)order[++cnt]=u;
	else tree_stak[++top]=u;
	inorder(t[u].rs);
}
void InitNode(int u){
	t[u].ls=t[u].rs=0;
	t[u].sz=t[u].tot=t[u].del=1;
}
void pushup(int u){
	t[u].sz=t[t[u].ls].sz+t[t[u].rs].sz+1;
	t[u].tot=t[t[u].ls].tot+t[t[u].rs].tot+1;
}
void build(int l,int r,int& u){
	int mid=(l+r)>>1;
	u=order[mid];
	if(l==r){
		InitNode(u);
		return ;
	}
	if(l<mid){
		build(l,mid-1,t[u].ls);
	}
	if(l==mid)t[u].ls=0;
	build(mid+1,r,t[u].rs);
	pushup(u);
	
}
void rebuild(int& u){
	cnt=0;
	inorder(u);
	if(cnt)build(1,cnt,u);
	else u=0;
}
bool notbalance(int u){
	if((double)t[u].sz*alpha<=(double)max(t[t[u].ls].sz,t[t[u].rs].sz)){
		return true;
	}
	return 0;
}
void Insert(int& u,int x){
	if(!u){
		u=tree_stak[top--];
		t[u].val=x;
		InitNode(u);
		return;
	}
	t[u].sz++;
	t[u].tot++;
	if(t[u].val>=x)Insert(t[u].ls,x);
	else Insert(t[u].rs,x);
	if(notbalance(u))rebuild(u);
}
int ranks(int u,int x){
	if(!u)return 0;
	if(x>t[u].val)return t[t[u].ls].sz+t[u].del+ranks(t[u].rs,x);
	return ranks(t[u].ls,x);
}
int kth(int k){
	int u=root;
	while(u){
		if(t[u].del&&t[t[u].ls].sz+1==k)return t[u].val;
		else if(t[t[u].ls].sz>=k)u=t[u].ls;
		else{
			k=k-t[t[u].ls].sz-t[u].del;
			u=t[u].rs;
		}
	}
	return t[u].val;
}
void Del_k(int & u,int k){
	t[u].sz--;
	if(t[u].del&&t[t[u].ls].sz+1==k){
		t[u].del=0;
		return;
	}
	if(t[t[u].ls].sz+t[u].del>=k)Del_k(t[u].ls,k);
	else Del_k(t[u].rs,k-t[t[u].ls].sz-t[u].del);
}
void Del(int x){
	Del_k(root,ranks(root,x)+1);
	if(t[root].tot*alpha>=t[root].sz)rebuild(root);
}
int main(){
for(int i=N-1;i>=1;i--)tree_stak[++top]=i;
int q;
cin>>q;
while(q--){
	int opt,x;
	cin>>opt>>x;
	if(opt==1){
		Insert(root,x);
	}else if(opt==2){
		Del(x);
	}else if(opt==3){
		printf("%lld\n",ranks(root,x)+1);
	}else if(opt==4){
		printf("%lld\n",kth(x));
	}else if(opt==5){
		printf("%lld\n",kth(ranks(root,x)));
	}else if(opt==6){
		printf("%lld\n",kth(ranks(root,x+1)+1));
	}
}	
	return 0;
}
2025/7/22 18:58
加载中...