BZOJ 3524 - 主席树
题目分析
标准主席树,按照位置插入每个数,对于询问l, r, 在l-1,r两树上按照线段树搜索次数大于(r - l + 1) / 2的数。
code
#include<bits/stdc++.h>
using namespace std;
const int N = 500050, M = 500050;
int n, m;
int a[N];
struct node{
int lc, rc, cnt;
}tr[N * 25];
int pool, rt[N];
namespace IO{
inline int read(){
int i = 0, f = 1; char ch = getchar();
for(; (ch < '0' || ch > '9') && ch != '-'; ch = getchar());
if(ch == '-') f = -1, ch = getchar();
for(; ch >= '0' && ch <= '9'; ch = getchar()) i = (i << 3) + (i << 1) + (ch -'0');
return i * f;
}
inline void wr(int x){
if(x < 0) putchar('-'), x = -x;
if(x > 9) wr(x / 10);
putchar(x % 10 + '0');
}
}using namespace IO;
inline void insert(int x, int &y, int l, int r, int v){
tr[y = ++pool] = tr[x];
tr[y].cnt++;
if(l == r) return;
int mid = l + r >> 1;
if(v <= mid) insert(tr[x].lc, tr[y].lc, l, mid, v);
else insert(tr[x].rc, tr[y].rc, mid + 1, r, v);
}
inline int query(int nl, int nr, int l, int r, int x){
// if(tr[nr].cnt - tr[nl].cnt < x) return 0;
if(l == r) return l;
int mid = l + r >> 1;
if(tr[tr[nr].lc].cnt - tr[tr[nl].lc].cnt >= x) return query(tr[nl].lc, tr[nr].lc, l, mid, x);
else if(tr[tr[nr].rc].cnt - tr[tr[nl].rc].cnt >= x) return query(tr[nl].rc, tr[nr].rc, mid + 1, r, x);
else return 0;
}
int main(){
freopen("h.in", "r", stdin);
n = read(), m = read();
for(int i = 1; i <= n; i++) a[i] = read(), insert(rt[i - 1], rt[i], 1, 500000, a[i]);
for(int i = 1; i <= m; i++){
int l = read(), r = read(), len = (r - l + 1) / 2;
int ans = query(rt[l - 1], rt[r], 1, 500000, len + 1);
wr(ans), putchar('\n');
}
return 0;
}