平衡树treap20分求调(QWQ)
查看原帖
平衡树treap20分求调(QWQ)
97737
Wsyflying2022楼主2022/1/22 08:03
#include <bits/stdc++.h>
#define reg register int
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
const int key=1e6;
struct Treap{
	ll val;
	int dat;
	int l,r;
	int cnt,size;
	#define val(x) a[x].val
	#define dat(x) a[x].dat
	#define l(x) a[x].l
	#define r(x) a[x].r
	#define cnt(x) a[x].cnt
	#define size(x) a[x].size
} a[maxn];
int n,tot,root;
ll INF=1e16+10,ans;
int New(ll val){
	val(++tot)=val;
	dat(tot)=rand();
	cnt(tot)=size(tot)=1;
	return tot;
}
inline int read(){
	reg x=0,f=1;
	char ch=getchar();
	while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar(); }
	while (isdigit(ch)) { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
	return x*f;
}
inline void Update(int p){
	size(p)=cnt(p)+size(l(p))+size(r(p));
}
inline void Build(){
	New(-INF); New(INF);
	root=1,r(1)=2; 
	Update(root);
}
inline void zig(int &p){
	int q=l(p);
	l(p)=r(q),r(q)=p,p=q;
	Update(r(p)),Update(p);
}
inline void zag(int &p){
	int q=r(p);
	r(p)=l(q),l(q)=p,p=q;
	Update(l(p)),Update(p);
}
inline void Insert(int &p,ll val){
	if (p==0){
		p=New(val);
		return ;
	}
	if (val==val(p)){
		cnt(p)++,Update(p);
		return ;
	}
	if (val<val(p)){
		Insert(l(p),val);
		if (dat(p)<dat(l(p))) zig(p);
	}
	else {
		Insert(r(p),val);
		if (dat(p)<dat(r(p))) zag(p);
	}
	Update(p);
}
inline int GetPre(int val){
	int ans=1;
	int p=root;
	while (p){
		if (val(p)==val) return p; 
		if (val(p)<=val && val(p)>val(ans)) ans=p;
		p=val<val(p) ? l(p) : r(p); 
	}
	return ans;
}
inline int GetNext(int val){
	int ans=2;
	int p=root;
	while (p){
		if (val(p)==val) return p;
		if (val(p)>=val && val(p)<val(ans)) ans=p;
		p=val>val(p) ? r(p) : l(p);
	}
	return ans;
}
inline int GetLarger(int p,ll val){
	int id=0;
	if (val(p)>=val) id=p;
	if (r(p) && !id) id=GetLarger(r(p),val);
	else if (l(p) && val(l(p))>=val) id=GetLarger(l(p),val);
	return id;
}
inline void Remove(int &p,ll val){
	if (p==0) return ;
	if (val!=val(p)){
		val<val(p) ? Remove(l(p),val) : Remove(r(p),val);
		Update(p);
		return ;
	}
	if (cnt(p)>1){
		cnt(p)--,Update(p);
		return ;
	} 
	if (l(p) || r(p)){
		if (!r(p) || dat(l(p))>dat(r(p))){
			zig(p);
			Remove(r(p),val);
		}
		else {
			zag(p);
			Remove(l(p),val);
		}
		Update(p);
	}
	else p=0;
	return ;
}
int main()
{
	srand(time(0));
	Build();
	n=read();
	for (reg i=1;i<=n;i++){
		reg opt;
		ll x;
	    opt=read();
	    scanf("%lld",&x);
	    switch (opt){
	    	case 0:
	    		Insert(root,x);
	    		break;
	    	case 1:
	    		int tmp1=GetPre(x),tmp2=GetNext(x);
	    		if (val(tmp1)==-INF && val(tmp2)==INF) break;
	    		if (x-val(tmp1)<=val(tmp2)-x) ans=(ans+x-val(tmp1))%key,Remove(root,val(tmp1));
	    		else ans=(ans+val(tmp2)-x)%key,Remove(root,val(tmp2));
	    		break;
		}
	}
	printf("%lld",ans%key);
	return 0;
}

2022/1/22 08:03
加载中...