[BZOJ1588][HNOI2002]营业额统计

原题地址

Splay.

AC code:

#include <cstdio>
const int N=500001;
int n,sigma,tot;

struct splaytree
{
    int val;
    splaytree *Prnt,*Ch[2];
}*root,t[N];

splaytree *NIL=&t[0];

void insert(splaytree**,int,splaytree *);
int min(int,int);
int pre(splaytree*);
int suc(splaytree*);

int main()
{
    root=NIL;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int temp;
        if(scanf("%d",&temp) == EOF) temp = 0;
        insert(&root,temp,NIL);
        if(root->Ch[0]==NIL&&root->Ch[1]==NIL) sigma=temp;
        else if(root->Ch[0]==NIL) sigma+=suc(root)-temp;
        else if(root->Ch[1]==NIL) sigma+=temp-pre(root);
        else sigma+=min(temp-pre(root),suc(root)-temp);
    }
    printf("%d",sigma);

    return 0;
}

int min(int x,int y)
{
    return x<y?x:y;
}

void rotate(splaytree *x,int type)
{
    splaytree *y=x->Prnt,*z=x->Prnt->Prnt;

    x->Ch[type^1]->Prnt=y;
    y->Ch[type]=x->Ch[type^1];
    y->Prnt=x;
    x->Ch[type^1]=y;
    x->Prnt=z;
    if(z!=NIL){
        if(z->Ch[0]==y) z->Ch[0]=x;
        else z->Ch[1]=x;
    }
}

void splay(splaytree *x)
{
    while(x->Prnt!=NIL){
        splaytree *y=x->Prnt,*z=x->Prnt->Prnt;
        if(z==NIL){
            if(y->Ch[0]==x) rotate(x,0);
            else rotate(x,1);
        }
        else{
            if(z->Ch[0]==y&&y->Ch[0]==x){
                rotate(y,0);
                rotate(x,0);
            }
            else if(z->Ch[1]==y&&y->Ch[1]==x){
                rotate(y,1);
                rotate(x,1);
            }
            else if(z->Ch[0]==y&&y->Ch[1]==x){
                rotate(x,1);
                rotate(x,0);
            }
            else{
                rotate(x,0);
                rotate(x,1);
            }
        }
    }
    root=x;
}

int pre(splaytree *x)
{
    splaytree *y=x->Ch[0];
    while(y->Ch[1]!=NIL) y=y->Ch[1];
    return y->val;
}

int suc(splaytree *x)
{
    splaytree *y=x->Ch[1];
    while(y->Ch[0]!=NIL) y=y->Ch[0];
    return y->val;
}

void insert(splaytree **p,int key,splaytree *last_p)
{
    if(*p==NIL){
        *p=&t[++tot];
        (*p)->val=key;
        (*p)->Prnt=last_p;
        (*p)->Ch[0]=(*p)->Ch[1]=NIL;
        splay(*p);
        return ;
    }
    if(key<=(*p)->val) insert(&(*p)->Ch[0],key,*p);
    else insert(&(*p)->Ch[1],key,*p);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值