[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;
}

總結

靈活使用平衡樹

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章