[HNOI2002]营业额统计

/*http://www.lydsy.com/JudgeOnline/problem.php?id=1588*/

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

const int maxn=2000005;

int L[maxn],R[maxn],S[maxn],V[maxn];

int n,p[maxn];
int cnt_node,root;

void Right_Rotate(int &t){
	int k=L[t];
	L[t]=R[k];
	R[k]=t;
	S[k]=S[t];
	S[t]=S[L[t]]+S[R[t]]+1;
	t=k;
}

void Left_Rotate(int &t){
	int k=R[t];
	R[t]=L[k];
	L[k]=t;
	S[k]=S[t];
	S[t]=S[L[t]]+S[R[t]]+1;
	t=k;
}

void maintain(int &t,bool flag){
	if(flag)
		if(S[R[R[t]]]>S[L[t]])
			Left_Rotate(t);
		else if(S[L[R[t]]]>S[L[t]])
			Right_Rotate(R[t]),Left_Rotate(t);
		else
			return ;
	else
		if(S[L[L[t]]]>S[R[t]])
			Right_Rotate(t);
		else if(S[R[L[t]]]>S[R[t]])
			Left_Rotate(L[t]),Right_Rotate(t);
		else
			return ;
	maintain(L[t],0);
	maintain(R[t],1);
	maintain(t,0);
	maintain(t,1);
}

void Init(){
	cnt_node=root=S[0]=0;
}

void Insert(int &t,int v){
	if(t){
		S[t]++;
		if(v<V[t])Insert(L[t],v);
		else Insert(R[t],v);
		maintain(t,v>=V[t]);
	}else{
		V[t=++cnt_node]=v;
		S[t]=1;
		L[t]=R[t]=0;
	}
}
/* v没有前驱的话就返回v 因为不知道是SBT中本身存在v
还是返回没有前驱,所以加一个p[maxn]标记一下*/

int Pred(int t,int v){
	if(!t)return v;
	if(v<=V[t]) return Pred(L[t],v);
	else{
		int tmp=Pred(R[t],v);
		return tmp==v?V[t]:tmp;
	}
}

int Succ(int t,int v){
	if(!t)return v;
	if(v>=V[t])return Succ(R[t],v);
	else{
		int tmp=Succ(L[t],v);
		return tmp==v?V[t]:tmp;
	}
}

int Min(int a,int b){
	return a<b?a:b;
}

int main(){
	int i,j,a,x,y;
	Init();
//	memset(p,0,sizeof(p));
	scanf("%d%d",&n,&a);
	Insert(root,a);
	int ans=a;
	p[a]=1;
	for(i=1;i<n;i++){
		if(scanf("%d",&a)==EOF)a=0;
		if(!p[a]){
			int x=a-Pred(root,a);
			int y=Succ(root,a)-a;
			Insert(root,a);
			if(x==0)x=maxn;if(y==0)y=maxn;
			ans+=Min(x,y);
			p[a]=1;
		}
	}
	printf("%d\n",ans);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值