[BZOJ1588][HNOI20220]营业额统计 splay

  1 #include<cstdio>
  2 #include<algorithm>
  3 #define inf 1000000000
  4 
  5 using namespace std;
  6 
  7 int n,ans=0,cnt=0,root;
  8 int r1,r2;
  9 
 10 struct tr{
 11     int val,son[2],fat;
 12 }tree[40000];
 13 
 14 void getsmall(int node,int x)
 15 {
 16     if(!node) return;
 17     if(tree[node].val>x) getsmall(tree[node].son[0],x);
 18     else
 19     {
 20         r1=tree[node].val;
 21         getsmall(tree[node].son[1],x);
 22     }
 23 }
 24 
 25 void getbig(int node,int x)
 26 {
 27     if(!node) return;
 28     if(tree[node].val<x) getbig(tree[node].son[1],x);
 29     else
 30     {
 31         r2=tree[node].val;
 32         getbig(tree[node].son[0],x);
 33     }
 34 }
 35 
 36 void turn(int x,int &rt)
 37 {
 38     int y=tree[x].fat,z=tree[y].fat;
 39     int l,r;
 40     if(tree[y].son[0]==x) l=0;
 41     else l=1;
 42     r=l^1;
 43     
 44     if(y==rt) rt=x;
 45     else
 46     {
 47         if(y==tree[z].son[0]) tree[z].son[0]=x;
 48         else tree[z].son[1]=x;
 49     }
 50     tree[x].fat=z; tree[y].fat=x; tree[tree[x].son[r]].fat=y;
 51     tree[y].son[l]=tree[x].son[r]; tree[x].son[r]=y;
 52 }
 53 
 54 void splay(int &rt,int x)
 55 {
 56     int y,z;
 57     
 58     while(rt!=x)
 59     {
 60         y=tree[x].fat;
 61         z=tree[y].fat;
 62         
 63         if(y!=rt)
 64         {
 65             if((tree[z].son[0]==y)^(tree[y].son[0]==x)) turn(x,rt);
 66             else turn(y,rt);
 67         }
 68         turn(x,rt);
 69     }
 70 }
 71 
 72 void ins(int &node,int val,int fat)
 73 {
 74     if(!node)
 75     {
 76         ++cnt;
 77         node=cnt;
 78         tree[node].val=val;
 79         tree[node].fat=fat;
 80         splay(root,node);
 81         return;
 82     }
 83     if(val<tree[node].val) ins(tree[node].son[0],val,node);
 84     else ins(tree[node].son[1],val,node);
 85 }
 86 
 87 int main()
 88 {
 89     scanf("%d",&n);
 90     
 91     for(int i=0;i<n;i++)
 92     {
 93         int x;
 94         if(scanf("%d",&x)==EOF) x=0;
 95         
 96         r1=-inf;r2=inf;
 97         
 98         getsmall(root,x);
 99         getbig(root,x);
100         
101         if(i) ans+=min(x-r1,r2-x);
102         else ans+=x;
103         
104         ins(root,x,0);
105     }
106     printf("%d",ans);
107     return 0;
108 }

 

posted @ 2017-06-15 14:10  2+c  阅读(158)  评论(0编辑  收藏  举报