BZOJ1208 [HNOI2004]宠物收养所

继续splay

我们删除和加点都要用splay维护

这样直接利用搜索树的性质模拟即可。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=8e4+5;
 4 const int mod=1e6;
 5 struct node
 6 {
 7     int l,r,w,f;
 8 }t[N];
 9 int n,cnt,rt,t1,t2,flag=-1;
10 void rotate(int x,int &k)
11 {
12     int y=t[x].f;int z=t[y].f;
13     if(y==k)k=x;
14     else{
15         if(t[z].l==y)t[z].l=x;else t[z].r=x;
16     }
17     if(t[y].l==x)t[t[x].r].f=y,t[y].l=t[x].r,t[x].r=y;
18     else t[t[x].l].f=y,t[y].r=t[x].l,t[x].l=y;
19     t[y].f=x;t[x].f=z;
20     return;
21 }
22 void splay(int x,int &k)
23 {
24     while(x!=k)
25     {
26         int y=t[x].f;int z=t[y].f;
27         if(y!=k){
28             if(t[y].l==x^t[z].l==y)rotate(x,k);
29             else rotate(y,k);
30         }
31         rotate(x,k);
32     }
33 }
34 void del(int x)
35 {
36     splay(x,rt);
37     if(t[x].l*t[x].r==0){rt=t[x].l+t[x].r;}
38     else{
39         int k=t[x].r;
40         while(t[k].l)k=t[k].l;
41         t[k].l=t[x].l;t[t[x].l].f=k;
42         rt=t[x].r;
43     }
44     t[rt].f=0;
45 }
46 void add(int &x,int w,int fa)
47 {
48     if(!x){t[x=++cnt].w=w;t[x].f=fa;splay(x,rt);return;}
49     else{
50         if(t[x].w<w)add(t[x].r,w,x);
51         else add(t[x].l,w,x);
52     }
53 }
54 void before(int p,int x)
55 {
56     if(!p)return;
57     if(t[p].w==x){t1=p;return;}
58     else if(t[p].w<x){t1=p;before(t[p].r,x);}
59     else before(t[p].l,x);
60 }
61 void after(int p,int x)
62 {
63     if(!p)return;
64     if(t[p].w==x){t2=p;return;}
65     else if(t[p].w>x){t2=p;after(t[p].l,x);}
66     else after(t[p].r,x);
67 }
68 int main()
69 {
70     scanf("%d",&n);int x,f;long long ans=0;
71     for(int i=1;i<=n;++i)
72     {
73         scanf("%d%d",&f,&x);
74         if(!rt){flag=f;add(rt,x,0);}
75         else if(flag==f){add(rt,x,0);}
76         else{
77             t1=t2=-1;
78             before(rt,x);after(rt,x);
79             if(t1==-1){ans+=abs(t[t2].w-x);ans%=mod,del(t2);}
80             else if(t2==-1){ans+=abs(x-t[t1].w);ans%=mod;del(t1);}
81             else{
82                 if(abs(t[t1].w-x)<=abs(t[t2].w-x))ans+=abs(t[t1].w-x),ans%=mod,del(t1);
83                 else ans+=abs(t[t2].w-x),ans%=mod,del(t2);
84             }
85         }
86     }
87     printf("%lld",ans);
88     return 0;
89 }

 

posted @ 2018-01-13 17:35  大奕哥&VANE  阅读(89)  评论(0编辑  收藏  举报