CODEVS1296

//treap 的简单应用

#include <iostream>
#include<stdio.h>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef long long ll;
int t1,t2;
struct node
{
    node *ch[2];
    int s,v,r;
    node(int v):v(v)
    {
        r=rand();
        s=1;
        ch[0]=ch[1]=NULL;
    }
    void maintain()
    {
        s=1;
        if(ch[0])
            s+=ch[0]->s;
        if(ch[1])
            s+=ch[1]->s;
    }
}*root;
void rotate(node* &o,int d)
{
    node *k=o->ch[d^1];
    o->ch[d^1]=k->ch[d];
    k->ch[d]=o;
    o->maintain();
    k->maintain();
    o=k;
}
void insert(node* &o,int v)
{
    if(o==NULL)
    {
        o=new node(v);
        o->maintain();
        return ;
    }
    int d=v<o->v?0:1;
    insert(o->ch[d],v);
    if(o->ch[d]->r>o->r)
        rotate(o,d^1);
    o->maintain();
}
void findsmall(node *o,int v)
{
    if(o==NULL)
        return;
    if(o->v>=v)
        findsmall(o->ch[0],v);
    else
    {
        t1=o->v;
        findsmall(o->ch[1],v);
    }
}
void findbig(node *o,int v)
{

    if(o==NULL)
        return;
    if(o->v<v)
        findbig(o->ch[1],v);
    else
    {
        t2=o->v;
       // cout<<"t2:"<<t2<<endl;
        findbig(o->ch[0],v);
    }
}


int main()
{
    int n;
    root=NULL;
    scanf("%d",&n);
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        if(i==1)
            ans+=x;
        else
        {
            t1=-999999999;
            t2=999999999;
            findsmall(root,x);
            findbig(root,x);
           // cout<<t1<<" "<<t2<<endl;
            int temp=min(abs(x-t1),abs(x-t2));
            ans+=temp;
        }
        insert(root,x);
    }
    printf("%d\n",ans);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值