【BZOJ1588】【HNOI2002】营业额统计 splay

题意就不赘述了。

做法:写一棵裸的平衡树,然后每次插入数值时询问前驱后继求差值取较小值加入答案。

直接看代码吧,没有多余的功能,想要splay模版的请点击标签页右上角。

#include <cstdio>
#include <cmath>
#include <algorithm>
#define is(x) (spt[spt[x].fa].son[1]==x)
#define N 501000
#define inf 0x3f3f3f3f
using namespace std;
struct SPT
{
	int fa,val,num,son[2];
	void cls(int f,int w)
	{
		son[0]=son[1]=0;
		val=w;
		fa=f;
		num=1;
	}
}spt[N];
int n,root,top,ans;
void link(int x,int y,int d){spt[y].son[d]=x;spt[x].fa=y;}
void rotate(int x)
{
	int y=spt[x].fa;
	int z=spt[y].fa;
	int id=is(x),idy=is(y);
	link(spt[x].son[!id],y,id);
	link(y,x,!id);
	if(z)link(x,z,idy);
	spt[x].fa=z;
}

void splay(int x)
{
	int y,z;
	while(y=spt[x].fa)
	{
		z=spt[y].fa;
		if(!z){rotate(x);break;}
		if(is(x)==is(y))rotate(y);
		else rotate(x);
		rotate(x);
	}
	root=x;
}
int pred()
{
	int x=spt[root].son[0];
	if(!x)return inf;
	while(spt[x].son[1])x=spt[x].son[1];
	return spt[x].val;
}
int succ()
{
	int x=spt[root].son[1];
	if(!x)return inf;
	while(spt[x].son[0])x=spt[x].son[0];
	return spt[x].val;
}
void newnode(int &x,int y,int w)
{
	x=++top;
	spt[x].cls(y,w);
}
bool insert(int w)
{
	if(spt[root].val==w)
	{
		spt[root].num++;
		return 1;
	}
	int x=root;
	while(spt[x].son[w>spt[x].val])
	{
		if(spt[x].val==w)
		{
			spt[x].num++;
			return 1;
		}
		x=spt[x].son[w>spt[x].val];
	}
	newnode(spt[x].son[w>spt[x].val],x,w);
	splay(spt[x].son[w>spt[x].val]);
	return 0;
}
int main()
{
	int i,j,k,temp;
	scanf("%d%d",&n,&temp);
	root=++top;
	spt[root].cls(0,temp);
	ans+=temp;
	for(i=1;i<n;i++)
	{
		if(scanf("%d",&temp)==EOF)temp=0;
		if(!insert(temp))ans+=min(abs(temp-pred()),abs(temp-succ()));
	}
	printf("%d\n",ans);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值