[Luogu1168]中位数

平衡树模板。。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <map>
 7 #include <string>
 8 #include <vector>
 9 #include <stack>
10 using namespace std;
11 
12 const int N=300000;
13 
14 int sz[N],v[N],ch[N][2],root,tot;
15 int newNode(int x){
16     tot++;
17     v[tot]=x;
18     sz[tot]=1;
19     return tot;
20 }
21 void up(int x){sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+1;}
22 
23 int merge(int a,int b){
24     if(!a||!b)return a|b;
25     if(rand()%(sz[a]+sz[b])<sz[a]){
26         ch[a][1]=merge(ch[a][1],b);
27         up(a);
28         return a;
29     }else{
30         ch[b][0]=merge(a,ch[b][0]);
31         up(b);
32         return b;
33     }
34 }
35 
36 typedef pair<int,int> sp;
37 sp split(int a,int k){
38     if(!a)return sp(0,0);
39     sp s;
40     if(sz[ch[a][0]]>=k){
41         s=split(ch[a][0],k);
42         ch[a][0]=s.second;
43         s.second=a;
44         up(a);
45     }else{
46         s=split(ch[a][1],k-sz[ch[a][0]]-1);
47         ch[a][1]=s.first;
48         s.first=a;
49         up(a);
50     }
51     return s;
52 }
53 
54 int ranks(int vv,int x=root){
55     if(!x)return 0;
56     if(v[x]<vv){
57         return ranks(vv,ch[x][1])+sz[ch[x][0]]+1;
58     }else{
59         return ranks(vv,ch[x][0]);
60     }
61 }
62 
63 void dfs(int x=root){
64     if(!x)return;
65     dfs(ch[x][0]);
66     cout<<v[x]<<' ';
67     dfs(ch[x][1]);
68 }
69 int n;
70 int main(){
71     srand(233);
72     scanf("%d",&n);
73     for(int i=1;i<=n;i++){
74         int x;scanf("%d",&x);
75         sp s=split(root,ranks(x));
76         root=merge(s.first,merge(newNode(x),s.second));
77         if(i&1){
78             sp s=split(root,i/2);
79             sp ss=split(s.second,1);
80             printf("%d\n",v[ss.first]);
81             root=merge(s.first,merge(ss.first,ss.second));
82         }
83     }
84 }
View Code

 

posted @ 2016-12-31 09:26  KingSann  阅读(83)  评论(0编辑  收藏  举报