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
| #include <bits/stdc++.h> using namespace std; typedef long long ll; #define per(i,a,n) for (int i=a;i<n;i++) #define rep(i,a,n) for (int i=n-1;i>=a;i--) const ll mod(998244353); const ll INF(0x3f3f3f3f3f3f3f3f); #define w(i) T[(i)].w #define ls(i) T[(i)].ls #define rs(i) T[(i)].rs ll powmod(ll a, ll b) { ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a%mod; a = a * a%mod; }return res; } const int MAXN(1e5+7);
int N, Q; int L[MAXN], R[MAXN];
struct node{ int ls,rs; ll w; node(){ls=rs=w=0;} }T[MAXN*20]; ll a[MAXN],b[MAXN],p[MAXN]; int root[MAXN],sz; int cmp(int i,int j){ return a[i]<a[j]; } int n,m; void ins(int &i,int l,int r,int x){ T[++sz]=T[i]; i=sz; w(i)++; if (l==r) return; int m=(l+r)>>1; if (x<=m) ins(ls(i),l,m,x); else ins(rs(i),m+1,r,x); } int query(int i,int j,int l,int r,int k){ if (l==r) return l; int t=w(ls(j))-w(ls(i)); int m=(l+r)>>1; if (t>=k) return query(ls(i),ls(j),l,m,k); else return query(rs(i),rs(j),m+1,r,k-t); }
inline ll solve(int& pos) { ll Ans=-1; ll lenn, lenn1, lenn3, summ; int rg=R[pos]-L[pos]+2; lenn=a[p[query(root[L[pos]-1], root[R[pos]], 1, N, rg-1)]]; lenn1=a[p[query(root[L[pos]-1], root[R[pos]], 1, N, rg-2)]]; summ = lenn+lenn1; per(i, 3, rg) { lenn3=a[p[query(root[L[pos]-1], root[R[pos]], 1, N, rg-i)]]; summ+=lenn3; if(lenn3+lenn1>lenn) { Ans=summ; break; } summ-=lenn; lenn = lenn1; lenn1 = lenn3; } return Ans; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
while(cin >> N >> Q) { n=N;m=Q; root[0]=0; per(i, 1, N+1) { cin >> a[i];p[i]=i; } sort(p+1, p+1+N, cmp); per(i, 1, N+1) {b[p[i]] = i;} sz=0; per(i, 1, N+1) { root[i]=root[i-1]; ins(root[i], 1, N, b[i]); } per(i, 1, Q+1) { cin >> L[i] >> R[i]; cout << solve(i) << '\n'; }
}
return 0; }
|