第一次用链表写splay,好不习惯,不会调,于是乎调得要死QAQ

还要orzLSJ神犇,代码实在太精练了

 1 #include<bits/stdc++.h>
 2 #define inc(i,l,r) for(i=l;i<=r;i++)
 3 #define dec(i,l,r) for(i=l;i>=r;i--)
 4 #define inf 1e9
 5 #define mem(a) memset(a,0,sizeof(a))
 6 using namespace std;
 7 int x,s,i,n;
 8 struct node *null;
 9 struct node{
10     int v;
11     node *c[2],*f;
12     node(int x,node *fa){
13         v=x;f=fa;c[0]=c[1]=null;
14     }
15     inline void set(node *ch,int d){
16         c[d]=ch;ch->f=this;
17     }
18     inline bool d(){
19         return this==f->c[1];
20     }
21 }*root;
22 void rot(node *x){
23     node *y=x->f;
24     int d=!x->d();
25     y->f->set(x,y->d());
26     y->set(x->c[d],!d);
27     x->set(y,d);
28     if(x->f==null)root=x;
29 }
30 void splay(node *x,node *goal){
31     for(node *y=x->f;y!=goal;y=x->f){
32         if(y->f!=goal)
33         x->d()!=y->d()?rot(x):rot(y);
34         rot(x);
35     }
36 }
37 int insert(int x){
38     node *r;
39     for(r=root;r->c[r->v<x]!=null;r=r->c[r->v<x])
40     if(r->v==x)return 1;
41     if(r->v==x)return 1;
42     r=r->c[r->v<x]=new node(x,r);
43     splay(r,null);
44     return 0;
45 }
46 int pre(){
47     if(root->c[0]==null)return -inf;
48     for(node *r=root->c[0];;r=r->c[1])
49     if(r->c[1]==null)return r->v;
50 }
51 int next(){
52     if(root->c[1]==null)return inf;
53     for(node *r=root->c[1];;r=r->c[0])
54     if(r->c[0]==null)return r->v;
55 }
56 int main(){
57     null=new node(-inf,NULL);
58     scanf("%d",&n);
59     inc(i,1,n){
60         scanf("%d",&x);
61         if(i==1){
62             s=x;
63             root=new node(x,null);
64         }else{
65             if(insert(x))continue;
66             int a=pre(),b=next();
67             s+=min(x-a,b-x);
68         }
69     }
70     printf("%d",s);
71     return 0;
72 }
View Code

 

posted on 2015-08-13 23:59  onlyRP  阅读(120)  评论(0编辑  收藏  举报