[HNOI2002] 营业额统计(平衡树splay)

题目:

我是超链接

题解:

rotate写挂了。。。此题不用计算size哦

代码:

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#define N 40005
#define INF 2e9
using namespace std;
int f[N+5],ch[N+5][2],cnt[N+5],key[N+5],root,sz;
bool ff1,ff2;
int get(int x){return ch[f[x]][1]==x;}
void rotate(int x)
{
	int old=f[x],oldf=f[old],which=get(x);
    ch[old][which]=ch[x][which^1]; f[ch[x][which^1]]=old;
    ch[x][which^1]=old; f[old]=x;
    f[x]=oldf;
    if (oldf) ch[oldf][ch[oldf][1]==old]=x;
}
void splay(int x)
{
	for (int fa;fa=f[x];rotate(x))
	  if (f[fa])
	    rotate(get(x)==get(fa)?fa:x);
	root=x;
}
int pre()
{
	if (cnt[root]>1) return key[root];
	int now=ch[root][0];
	if (!now) return -INF;
	while (ch[now][1]) now=ch[now][1];
	return key[now];
}
int next()
{
	if (cnt[root]>1) return key[root];
	int now=ch[root][1];
	if (!now) return INF;
	while (ch[now][0]) now=ch[now][0];
	return key[now];
}
void insert(int x)
{
	if (root==0)
	{
		root=++sz; f[sz]=ch[sz][0]=ch[sz][1]=0; key[sz]=x; 
	}
	int now=root,fa=0;
	while (1) {
		if (x==key[now]) {
			cnt[now]++;
			splay(now);
			return;
		}
		fa=now;
		now=ch[now][key[now]<x];
		if(now==0) {
			sz++;
			f[sz]=fa;
			ch[sz][0]=ch[sz][1]=0;
			key[sz]=x;
			cnt[sz]=1;
			ch[fa][key[fa]<x]=sz;
			splay(sz);
			break;
		}
	}
}
int main()
{
	int n,i,b,ans=0;
	scanf("%d",&n);
	for (i=1;i<=n;i++)
	{
		if (scanf("%d",&b)==EOF) b=0;
		insert(b);
		if (i==1) 
		{
			ans+=b;continue;
		}
		int a1=pre(),a2=next();
		ans+=min(abs(a1-b),abs(b-a2));		
	}
	printf("%d",ans);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值