1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include "bits/stdc++.h"
using namespace std; const int N = 3e5 + 10;
struct Tree { int *sum, *ls, *rs; int n, cnt;
Tree(int n) { sum = new int[n << 5]; ls = new int[n << 5]; rs = new int[n << 5]; cnt = 0; }
int build(int l, int r) { int rt = ++cnt; sum[rt] = 0; if (l < r) { int mid = (l + r) >> 1; ls[rt] = build(l, mid); rs[rt] = build(mid + 1, r); }
return rt; }
int update(int pre, int l, int r, int x) { int rt = ++cnt; ls[rt] = ls[pre], rs[rt] = rs[pre], sum[rt] = sum[pre] + 1; if (l < r) { int mid = (l + r) >> 1; if (x <= mid) ls[rt] = update(ls[pre], l, mid, x); else rs[rt] = update(rs[pre], mid + 1, r, x); }
return rt; }
int query(int u, int v, int l, int r, int lim) { if (l >= r) return sum[v] - sum[u]; if (sum[v] - sum[u] <= lim) return 0; int x = sum[ls[v]] - sum[ls[u]], y = sum[rs[v]] - sum[rs[u]];
int mid = (l + r) >> 1; int res; if (x > lim && (res = query(ls[u], ls[v], l, mid, lim)) > lim) return res; if (y > lim && (res = query(rs[u], rs[v], mid + 1, r, lim)) > lim) return res; return 0; } };
int n, q, m; int a[N], b[N], rt[N];
int main() { cin >> n >> q; for (int i = 1; i <= n; i++) { scanf("%d", a + i); b[i] = a[i]; }
sort(b + 1, b + 1 + n); m = unique(b + 1, b + 1 + n) - (b + 1);
Tree t(N); rt[0] = t.build(1, m); for (int i = 1; i <= n; i++) { int p = lower_bound(b + 1, b + 1 + m, a[i]) - b; rt[i] = t.update(rt[i - 1], 1, m, p); }
while (q--) { int l, r; scanf("%d%d", &l, &r); int lim = ceil((r - l + 1.0) / 2); int f = t.query(rt[l - 1], rt[r], 1, m, lim);
printf("%d\n", max(1, 2 * f - (r - l + 1))); } }
|