蒟蒻的LJ代码。。。求调(FHQ Treap)!!!
查看原帖
蒟蒻的LJ代码。。。求调(FHQ Treap)!!!
856459
yangjunhan1楼主2023/8/16 11:19
#include<bits/stdc++.h>
using namespace std;
const int N=1e6;
int t[N],h[N],tot,cnt[N],sz[N],v[N],n,ls[N],rs[N],root,hm[N];
void sizup(int x){
	sz[x]=sz[ls[x]]+sz[rs[x]]+cnt[x];
}
void fl(int rt,int &l,int &r,int x){
	if(!rt){
		l=r=0;
		return ;
	}
	if(v[rt]<=x){
		l=rt;
		fl(rs[rt],rs[l],r,x);
		sizup(l);
	}
	else{
		r=rt;
		fl(ls[rt],l,ls[r],x);
		sizup(r);
	}
}
int hb(int l,int r){
	if(!l || !r)	return l+r;
	if(h[l]<h[r]){
		rs[l]=hb(rs[l],r);
		sizup(l); 
		return l;
	}
	else{
		ls[r]=hb(l,ls[r]);
		sizup(r);
		return r;
	}
}
int cr(int x){
	if(!root){
		tot++;
		sz[tot]=cnt[tot]=1;
		v[tot]=x;
		hm[x]=tot;
		h[tot]=rand();
		return tot;
	}
	int l,r,i;
	fl(root,l,r,x);
	fl(l,l,i,x-1);
	if(i){
		cnt[i]++;
		sizup(i);
	} 
	else{
		tot++;
		sz[tot]=cnt[tot]=1;
		v[tot]=x;
		hm[x]=tot;
		i=tot;
		sizup(tot);
	}
	return hb(hb(l,i),r);
}
void sc(int x){
	int k,l,r;
	fl(root,l,r,x);
	fl(l,k,l,x-1);
	if(l){
		cnt[l]--;
		sizup(l);
		if(cnt[l])
			root=hb(k,hb(l,r));
		else	root=hb(k,r);
	}
	else	root=hb(k,r);
}
int pm(int x){
	int l,r;
	fl(root,l,r,x);
	int ans=sz[l]+1;
	hb(l,r);
	return ans;
}
void pmfl(int rt,int &l,int &r,int x){
	if(!rt){
		l=r=0;
		return ;
	}
	if(ls[rt]<x){
		l=ls[rt];
		pmfl(ls[rt],rs[l],r,x-sz[ls[rt]]-cnt[rt]);
		sizup(l);
	}
	else{
		r=rs[rt];
		pmfl(rs[rt],l,ls[r],x);
		sizup(r);
	}
}
int pms(int x){
	int l,r,k;
	pmfl(root,l,r,x-1);
	pmfl(r,r,k,1);
	int ans=v[r];
	root=hb(hb(l,r),k);
	return ans;
}
int qq(int x){
	return pms(pm(x)-1);
}
int hj(int x){
	return pms(pm(x)+cnt[hm[x]]);
}
int main(){
	cin>>n;
	while(n--){
		int op,x;
		cin>>op>>x;
		if(op==1)	root=cr(x);
		if(op==2)	sc(x);
		if(op==3)	cout<<pm(x)<<endl;
		if(op==4)	cout<<pms(x)<<endl;
		if(op==5)	cout<<qq(x)<<endl;
		if(op==6)	cout<<hj(x)<<endl;
	}
	return 0;
}
2023/8/16 11:19
加载中...