自己的splay模版(bzoj1588)

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1000005;
const int inf=0x3f3f3f3f;
int id=0,ch[maxn][2],w[maxn],fa[maxn],root,n;
void rotate(int x)///重要的rotate操作
{
	int y=fa[x],z=fa[y],l,r;
	
	if (ch[y][0]==x) l=0;else l=1;r=l^1;
	
	if (z) if (ch[z][0]==y) ch[z][0]=x;else ch[z][1]=x;
	fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
	ch[y][l]=ch[x][r];ch[x][r]=y;
}
void splay(int x,int k)/splay操作!!,这两点最为重要
{
	int y=fa[x],z=fa[y];
	while (fa[x]!=k)
	{
		y=fa[x];z=fa[y];
		if (z!=k)
		{
			if ((ch[z][0]==y)^(ch[y][0]==x)) rotate(x);else rotate(y);
		}
		rotate(x);
	}
	if (k==0) root=x;//root在这里更新
}
以上一般不变
void insert(int x,int v)
{
	int y;
	while (true)
	{
		y=ch[x][v>w[x]];
		if (y==0)
		{
			fa[++id]=x;
			w[id]=v;
			ch[x][v>w[x]]=id;
			x=id;
			break;
		}
		x=y;
	}
	splay(x);
}///还是用while来插入
int pre(int x)
{
	int y=ch[x][0];
	while (ch[y][1]) y=ch[y][1];
	return w[y];
}
int nex(int x)
{
	int y=ch[x][1];
	while (ch[y][0]) y=ch[y][0];
	return w[y];
}
int main()
{
	scanf("%d",&n);
	int t;
	if (scanf("%d",&t)==-1) t=0;
	memset(ch,0,sizeof(ch));
	memset(w,0,sizeof(w));
	memset(fa,0,sizeof(fa));
	id=1;root=1;
	ch[1][0]=ch[1][1]=0;fa[1]=0;
	w[1]=t;
	insert(root,inf);insert(root,-inf);
	
	int ans=t;
	for (int i=2;i<=n;i++)
	{
		if (scanf("%d",&t)==-1) t=0;
		insert(root,t);
		int a,b;
		a=pre(root);b=nex(root);
		ans+=min(t-a,b-t);
	}
	printf("%d",ans);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值