#include using namespace std; #define all(v) (v).begin(),(v).end() #define pb(a) push_back(a) #define rep(i, n) for(int i=0;i node; ll ID = 0; // min -> INF, max, sum -> 0 inline ll func(ll a, ll b){return a + b;} ///////// public: SegmentTree(vector v) { int sz = v.size(); n = 1; while(n < sz) n *= 2; node.resize(2*n-1, ID); for(int i=0; i=0; i--) node[i] = func(node[2*i+1], node[2*i+2]); } void add(ll x, ll val) { x += (n - 1); node[x] += val; while(x > 0) { x = (x - 1) / 2; node[x] = func(node[2*x+1], node[2*x+2]); } } ll get(ll a, ll b, ll k=0, ll l=0, ll r=-1) { if(r < 0) r = n; if(r <= a || b <= l) return ID; if(a <= l && r <= b) return node[k]; ll vl = get(a, b, 2*k+1, l, (l+r)/2); ll vr = get(a, b, 2*k+2, (l+r)/2, r); return func(vl, vr); } }; int main() { cin.tie(0); ios::sync_with_stdio(false); ll n, q; cin >> n >> q; vector> v; SegmentTree seg_(vector (n, 0)); rep(i, n) { ll a; cin >> a; seg_.add(i, a); v.push_back({a, i}); } sort(all(v)); vector> task; rep(i, q) { ll le, ri; cin >> le >> ri; task.push_back({0LL, -1LL << 30, 1LL << 30, le - 1, ri, i}); } sort(all(task)); bool f = true; vector> query; while(f) { vector> nx; int id = 0; f = false; SegmentTree seg(vector (n, 0)); for(auto [mid, Min, Max, le, ri, i] : task) { while(id < n and v[id].first <= mid) { seg.add(v[id].second, 1); id ++; } if(seg.get(le, ri) * 2 >= (ri - le)) Max = mid; else Min = mid; ll m = (Max + Min) / 2; if(m == Min) { query.push_back({Max, le, ri, i}); continue; } f = true; nx.push_back({m, Min, Max, le, ri, i}); } swap(nx, task); sort(all(task)); } sort(all(query)); vector ans(q); { int id = 0; SegmentTree seg(vector (n, 0)), seg_cnt(vector (n, 0)); for(auto [m, le, ri, i] : query) { while(id < n and v[id].first <= m) { seg_cnt.add(v[id].second, 1); seg.add(v[id].second, - v[id].first); id ++; } ans[i] = seg_.get(le, ri) + seg.get(le, ri) * 2 - m * (ri - le) + m * 2 * seg_cnt.get(le, ri); } } rep(i, q) { cout << ans[i] << endl; } return 0; }