[luoguP1168]中位数(主席树+离散化)
模板题一道,1A。
——代码
1 #include <cstdio> 2 #include <algorithm> 3 #define ls son[now][0], l, mid 4 #define rs son[now][1], mid + 1, r 5 6 using namespace std; 7 8 const int N = 100005; 9 10 int n, sz, tot; 11 int a[N], b[N], sum[20 * N], rt[20 * N], son[20 * N][2]; 12 13 inline void build(int &now, int l, int r) 14 { 15 now = ++tot; 16 if(l == r) return; 17 int mid = (l + r) >> 1; 18 build(ls); 19 build(rs); 20 } 21 22 inline void update(int &now, int l, int r, int last, int x) 23 { 24 now = ++tot; 25 sum[now] = sum[last] + 1; 26 son[now][0] = son[last][0]; 27 son[now][1] = son[last][1]; 28 if(l == r) return; 29 int mid = (l + r) >> 1; 30 if(x <= mid) update(ls, son[now][0], x); 31 else update(rs, son[now][1], x); 32 } 33 34 inline int query(int now, int l, int r, int x) 35 { 36 if(l == r) return l; 37 int mid = (l + r) >> 1, cnt = sum[son[now][0]]; 38 if(x <= cnt) return query(ls, x); 39 else return query(rs, x - cnt); 40 } 41 42 int main() 43 { 44 int i, k; 45 scanf("%d", &n); 46 for(i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i]; 47 sort(b + 1, b + n + 1); 48 sz = unique(b + 1, b + n + 1) - (b + 1); 49 build(rt[0], 1, sz); 50 for(i = 1; i <= n; i++) 51 { 52 k = lower_bound(b + 1, b + sz + 1, a[i]) - b; 53 update(rt[i], 1, sz, rt[i - 1], k); 54 if(i % 2 == 1) printf("%d\n", b[query(rt[i], 1, sz, (i + 1) >> 1)]); 55 } 56 return 0; 57 }