BZOJ【1588】营业额统计 Treap

传送门
平衡树求前驱和后继,可以用set
AC code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
struct Treap
{
	int l,r,key,size,w,rnd;
}T[33005];
int root,n,size,ans;
const int rndd=2000000001;
int tot;
void update(int k)
{
	T[k].size=T[T[k].l].size+T[T[k].r].size+T[k].w;
}
void zig(int &k)
{
	int t=T[k].r;
	T[k].r=T[t].l;
	T[t].l=k;
	T[t].size=T[k].size;
	update(k);
	k=t;
}
void zag(int &k)
{
	int t=T[k].l;
	T[k].l=T[t].r;
	T[t].r=k;
	T[t].size=T[k].size;
	update(k);
	k=t;
}
void insert(int &k,int x)
{
	if(!k)
	{
		size++;
		k=size;
		T[k].size=T[k].w=1;
		T[k].rnd=rand();
		T[k].key=x;
		return ;
	}
	T[k].size++;
	if(T[k].key==x)
	{
		T[k].w++;
		return ;
	}
	if(T[k].key>x)
	{
		insert(T[k].l,x);
		if(T[T[k].l].rnd<T[k].rnd)zag(k);
	}
	else 
	{
		insert(T[k].r,x);
		if(T[T[k].r].rnd<T[k].rnd)zig(k);
	}
}
void query_sub(int &k,int x)
{
	//cout<<k<<" "<<T[k].key<<endl;
	if(!k)return ;
	if(x==T[k].key)
	{
		ans=x;
		return ;
	}
	if(x<T[k].key)
	{
		ans=T[k].key;
		//cout<<ans<<"a"<<endl;
		query_sub(T[k].l,x);
	}
	else query_sub(T[k].r,x);
}
void query_pro(int &k,int x)
{
	//cout<<k<<" "<<T[k].key<<endl;
	if(!k)return ;
	if(x==T[k].key)
	{
		ans=x;
		return ;
	}
	if(x>T[k].key)
	{
		ans=T[k].key;
		//cout<<ans<<"b"<<endl;
		query_pro(T[k].r,x);
	}
	else query_pro(T[k].l,x);
}
int main()
{
	srand(21323123);
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		//cout<<"x";
		int x;
		scanf("%d",&x);
		if(i==1)
		{
			insert(root,x);
			tot+=x;
			continue;
		}
		int minn=2000000000;
		ans=rndd;
		query_pro(root,x);
		if(ans!=rndd)
		minn=min(minn,abs(ans-x));
		//cout<<ans<<endl;
		ans=rndd;
		query_sub(root,x);
		if(ans!=rndd)
		minn=min(minn,abs(ans-x));
		//cout<<ans<<endl;
		tot+=minn;
		insert(root,x);
		//cout<<root<<endl;
		//cout<<tot<<"s"<<endl;
	}
	printf("%d",tot);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值