现在的位置: 首页 > 综合 > 正文

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

2016年09月23日 ⁄ 综合 ⁄ 共 1420字 ⁄ 字号 评论关闭

题意就不赘述了。

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

直接看代码吧,没有多余的功能,想要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;
}

抱歉!评论已关闭.