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

题目

传送门

题解

比平衡树模板还要简单的板子题;
就是每次插入一个元素,求其前驱和后继即可,求差累加较小值即可;我们可以事先再平衡树中插入 -inf 和 inf;
注意元素是课重复的,cnt数组就不要用了

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=1e5;
const int inf=1e9;
int read(){
    char ch=getchar(); int now=0,f=1;
    while (ch<'0' || ch>'9') {if (ch=='-') f=-1; ch=getchar();}
    while (ch>='0'&&ch<='9') {now=(now<<1)+(now<<3)+ch-'0'; ch=getchar();}
    return now*f;}
int n,a[maxn],f[maxn],ch[maxn][2],size[maxn],cnt[maxn],key[maxn],sz,rt;

int Abs(int x) {return x<0?-x:x;}
bool get(int x) {return ch[f[x]][1]==x;}
void clear(int x) {f[x]=ch[x][1]=ch[x][0]=size[x]=cnt[x]=key[x]=0;}
void pushup(int x)
{
    if (!x) return;
    size[x]=cnt[x]+size[ch[x][0]]+size[ch[x][1]];
}
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;
    pushup(old); pushup(x);
}

void splay(int x,int goal)
{
    for (int fa; (fa=f[x])!=goal; rotate(x))
        if (f[fa]!=goal) 
            rotate(get(x)==get(fa) ?fa:x);
    if (!goal) rt=x;
}

void insert(int x)
{
    if (rt==0)
    {
        sz++; key[sz]=x; rt=sz;
        cnt[sz]=size[sz]=1;
        f[sz]=ch[sz][1]=ch[sz][0]=0;
        return;
    }
    int now=rt,fa=0;
    while (1)
    {
        fa=now; now=ch[now][x>key[now]];
        if (now==0)
        {
            sz++; //这里不要更新rt 
            cnt[sz]=size[sz]=1;
            ch[sz][0]=ch[sz][1]=0;
            ch[fa][x>key[fa]]=sz;
            f[sz]=fa;
            key[sz]=x;
            pushup(fa); splay(sz,0); return;
        }
    }
}

int pre()
{
    int now=ch[rt][0];
    while (ch[now][1]) now=ch[now][1];
    return now;
}
int next()
{
    int now=ch[rt][1]; if (!now) return 2*inf;
    while (ch[now][0]) now=ch[now][0];
    return now;
}

int ans;
int main()
{
    n=read();
    insert(-inf); insert(inf);
    for (int i=1; i<=n; i++)
    {
        int x=read(); insert(x);
        if (i==1) {ans=x; continue;}
        int pr=key[pre()]; int nx=key[next()];

        int d=min(Abs(x-pr),Abs(x-nx));
        ans+=d;
    }
    printf("%d",ans);
    return 0;
}

总结

灵活使用平衡树

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值