bzoj1588 [HNOI2002]营业额统计 (Splay)

本文详细解析了一个Splay树的应用实例,重点介绍了Splay树的基本操作及其实现细节,包括节点旋转、查找最邻近节点等关键步骤,并分享了调试过程中遇到的问题及解决方法。

题意:中文题。。不多说。

这题就是裸的Splay模板。。。但是出了一个问题。。导致我WA了12次(最后随机数对拍才找到)。。。

没插入一个点,把这个点旋转到根,然后找到根的左子树最靠右边的的,根的右子树最靠左边的点,然后相减处理下就好。。。

这里我是WA在,每把一个点旋转到根,忘记把表示根节点的那个点修改成根了。。。然后还RE了几发,原因是我写的是多组数据(测试是单组数据),然后我需要初始化,删除整个树的时候指针可能越界访问了。。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN=500010;
struct Node
{
	Node *ch[2];
	Node *fa;
	int val;
}p[MAXN];
Node *null=&p[0];
int tot;
Node *root=null;
void Rotate(Node *x,int c)
{
	Node *y=x->fa;
	y->ch[!c]=x->ch[c];
	if(x->ch[c]!=null)
		x->ch[c]->fa=y;
	x->fa=y->fa;
	if(y->fa!=null)
	{
		if(y->fa->ch[0]==y)
			y->fa->ch[0]=x;
		else
			y->fa->ch[1]=x;
	}
	y->fa=x;
	x->ch[c]=y;
	if(y==root)
		x=root;
}
void splay(Node *x,Node *f)
{
	while(x->fa!=f)
	{
		if(x->fa->fa==f)
		{
			if(x->fa->ch[0]==x)
				Rotate(x,1);
			else
				Rotate(x,0);
		}
		else
		{
			Node *y=x->fa,*z=y->fa;
			if(z->ch[0]==y)
			{
				if(y->ch[0]==x)
					Rotate(y,1),Rotate(x,1);
				else
					Rotate(x,0),Rotate(x,1);
			}
			else
			{
				if(y->ch[1]==x)
					Rotate(y,0),Rotate(x,0);
				else
					Rotate(x,1),Rotate(x,0);
			}
		}
	}
}
Node *new_Node(int val)
{
	Node *rt=&p[++tot];
	rt->ch[0]=rt->ch[1]=rt->fa=null;
	rt->val=val;
	return rt;
}
Node *root1=null;
Node *insert(Node *rt,int val)
{
	if(rt==null)
	{
		rt=new_Node(val);
		root1=rt;
		return rt;
	}
	if(rt->val==val)
		return rt;
	if(rt->val>val)
	{
		rt->ch[0]=insert(rt->ch[0],val);
		rt->ch[0]->fa=rt;
	}
	else
	{
		rt->ch[1]=insert(rt->ch[1],val);
		rt->ch[1]->fa=rt;
	}
	return rt;
}
Node *Delete(Node *&rt)
{
	if(rt==null)
		return null;
	if(rt->ch[0]!=null)
		rt->ch[0]=Delete(rt->ch[0]);
	if(rt->ch[1]!=null)
		rt->ch[1]=Delete(rt->ch[1]);
	rt=null;
	return rt;
}
int main()
{
	int n,i;
	null->val=0;
	//freopen("out.txt","r",stdin);
	//freopen("out1.txt","w",stdout);
	while(scanf("%d",&n)==1)
	{
		tot=0;
		int x;
		int ans=0;
		for(i=1;i<=n;i++)
		{
			x=0;
			scanf("%d",&x);
			root1=null;
			root=insert(root,x);
			if(root1==null)
				continue;
			splay(root1,null);
			root=root1;	//根节点要随着相应的改变
			if(i==1)
			{
				ans+=x;
				continue;
			}
			Node *L,*R;
			L=root1->ch[0];
			while(L!=null&&L->ch[1]!=null)
				L=L->ch[1];
			R=root1->ch[1];
			while(R!=null&&R->ch[0]!=null)
				R=R->ch[0];
			int temp1=1<<30,temp2=1<<30;
			if(L!=null)
				temp1=x-(L->val);
			if(R!=null)
				temp2=(R->val)-x;
			int temp=min(temp1,temp2);
			ans+=temp;
		}
		printf("%d\n",ans);
		root=Delete(root1);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值