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 86 87 88 89 90 91 92 93 94 95
| #include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <string> #include <set> #include <queue>
using namespace std; const int N = 1000005; const int maxn = 2500005; int rt[N << 4], ls[N << 4], rs[N << 4],a[N], b[N],sum[N << 4];
int tot; void build(int &o, int l, int r) { o = ++tot; sum[o] = 0; if(l == r) return; int mid = (l + r) >> 1; build(ls[o], l, mid); build(rs[o], mid + 1, r); }
void update(int &o, int l, int r, int last, int k) { o = ++tot; ls[o] = ls[last]; rs[o] = rs[last]; sum[o] = sum[last] + 1; if(l == r) return; int mid = (l + r) >> 1; if(k <= mid) update(ls[o], l, mid, ls[last], k); else update(rs[o], mid + 1, r, rs[last], k); }
int query(int ss, int tt, int l, int r, int k) { if(l == r) return l; int cnt = sum[ls[tt]] - sum[ls[ss]]; int mid = (l + r) >> 1; if(k <= cnt) return query(ls[ss],ls[tt],l, mid, k); else return query(rs[ss],rs[tt],mid + 1, r, k - cnt); } int main() { int t,n,Q,ll,rr,k;
while(scanf("%d %d",&n,&Q) != EOF) { tot = 0; for(int i = 1; i <= n; ++i) { scanf("%d",&a[i]); } memcpy(b,a,sizeof(a)); sort(b + 1, b + n + 1); int sz = unique(b + 1, b + n + 1) - (b + 1); build(rt[0],1,sz); for(int i = 1; i <= n; ++i) { a[i] = lower_bound(b + 1, b + sz + 1, a[i]) - b; } for(int i = 1; i <= n; ++i) { update(rt[i],1,sz,rt[i - 1], a[i]); } while(Q--) { scanf("%d %d",&ll,&rr); long long num = -1, q[55]; for(int i = 1; i <= min(50, rr - ll + 1); ++i) { q[i] = b[query(rt[ll - 1], rt[rr], 1,sz, rr - ll + 2 - i)]; if(q[i] + q[i - 1] > q[i - 2] && i >= 3) { num = q[i - 1] + q[i - 2] + q[i]; break; } } printf("%lld\n",num); } }
}
|