CODEVS1296

来源:互联网 发布:ps制作淘宝店招教程 编辑:程序博客网 时间:2024/06/08 19:51

//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