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 84 85
|
#include<bits/stdc++.h> using namespace std;
const int Ma = 1e5 + 100; int pa[Ma]; int ans[Ma];
struct Qes{ int l, r, k, cx; bool operator < (const Qes b) const{ if(k != b.k)return k < b.k; else return r < b.r; } }Q[Ma];
struct Bit{ int N; int *tree; void init(int n){ N = n; tree = new int[n + 1](); } int lowbit(int x){ return x & -x; } void add(int pos, int val){ while(pos <= N){ tree[pos] += val; pos += lowbit(pos); } } int sum(int pos){ int ans =0; while(pos > 0){ ans += tree[pos]; pos -= lowbit(pos); } return ans; } }bit;
int main(){ int n, q; while(~scanf("%d%d", &n, &q)){ for(int i = 1; i <= n; i++) scanf("%d", pa + i); int aim = sqrt(n); for(int a, b, i = 0; i < q; i++){ scanf("%d%d", &a, &b); Q[i].l = a, Q[i].r = b; Q[i].k = a / aim, Q[i].cx = i; } sort(Q, Q + q); int cnt = 0, le = 1, ri = 0; bit.init(n); for(int i = 0; i < q; i++){ for(; le < Q[i].l; le++) bit.add(pa[le], -1), cnt--; for(--le; le >= Q[i].l; le--) bit.add(pa[le], 1), cnt++; for(; ri > Q[i].r; ri--) bit.add(pa[ri], -1), cnt--; for(ri++; ri <= Q[i].r; ri++) bit.add(pa[ri], 1), cnt++; int l = 0, r = n; while(l <= r){ int mid = (l + r) / 2; if(cnt - bit.sum(mid - 1) < mid)r = mid - 1; else l = mid + 1; } ans[Q[i].cx] = r; le = Q[i].l, ri = Q[i].r; } for(int i = 0; i < q; i++) printf("%d\n", ans[i]); } return 0; }
|