bzoj 1588 splay模板题

      用晚自习学了一下splay模板,没想象中那么难,主要是左旋和右旋可以简化到一个函数里边,减少代码长度。。。

     

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #define maxn 33333
 6 #define inf 0x3f3f3f3f
 7 #define lc(x) ch[(x)][0]
 8 #define rc(x) ch[(x)][1]
 9 using namespace std;
10 int fa[maxn],ch[maxn][2],root,k[maxn],ind=1;
11 inline void rotate(int p)
12 {
13    int q=fa[p],y=fa[q],x=ch[q][1]==p;
14    ch[q][x]=ch[p][x^1];fa[ch[q][x]]=q;
15    ch[p][x^1]=q;fa[q]=p;
16    fa[p]=y;
17    if(y)
18    {
19        if(ch[y][0]==q)ch[y][0]=p;
20        else ch[y][1]=p;
21    }
22 }
23 inline void splay(int x)
24 {
25     for(int y;y=fa[x];rotate(x))
26     {
27         if(fa[y])
28         {
29             if(y==lc(fa[y])&&x==lc(y)||(y==rc(fa[y])&&x==rc(y)))rotate(y);
30             else rotate(x);
31         }
32     }
33     root=x;
34 }
35 void insert(int x,int v)
36 {
37      while(ch[x][k[x]<v])x=ch[x][k[x]<v];
38      ch[x][k[x]<v]=++ind;
39      fa[ind]=x;k[ind]=v;splay(ind);
40 }
41 inline int pre(int x)
42 {
43     int tmp=ch[x][0];
44     while(ch[tmp][1])tmp=ch[tmp][1];
45     return k[tmp];
46 }
47 inline int suc(int x)
48 {
49     int tmp=ch[x][1];
50     while(ch[tmp][0])tmp=ch[tmp][0];
51     return k[tmp];
52 }
53 int main()
54 {
55     int t;int n;
56     int ans=0;
57     scanf("%d",&n);
58     if(scanf("%d",&t)==-1)t=0;
59     root=1;k[root]=t;
60     ans=t;
61     insert(root,inf);insert(root,-inf);
62     for(int i=2;i<=n;i++)
63     {
64         if(scanf("%d",&t)==-1)t=0;
65         insert(root,t);
66         int a=pre(root);int b=suc(root);
67         ans+=min(t-a,b-t);
68     }
69     printf("%d\n",ans);
70     return 0;
71 }

 

posted @ 2016-12-03 22:19  SD_le  阅读(277)  评论(3编辑  收藏  举报
重置按钮