#include #include using namespace std; using namespace atcoder; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int N, Q; cin >> N >> Q; vector a(N), c; for(auto &&v : a) cin >> v; c = a; sort(c.begin(), c.end()); c.erase(unique(c.begin(), c.end()), c.end()); int m = c.size(); vector> tb(m); for(int i = 0; i < m; i++){ int p = lower_bound(c.begin(), c.end(), a[i]) - c.begin(); tb[p].emplace_back(i); } vector> query(Q); vector ng(Q, -1), ok(Q, m - 1); vector> que(m); for(auto &&[l, r] : query){ cin >> l >> r; l--; } for(int i = 0; i < Q; i++) que[m / 2].push(i); for(int i = 0; i < 18; i++){ fenwick_tree fw(N); for(int j = 0; j < m; j++){ for(auto p : tb[j]) fw.add(p, 1); while(!que[j].empty()){ auto qi = que[j].front(); que[j].pop(); auto [l, r] = query[qi]; if(fw.sum(l, r) >= (r - l + 1) / 2){ ok[qi] = j; }else{ ng[qi] = j; } if(ng[qi] + 1 < ok[qi]){ int mid = (ok[qi] + ng[qi]) / 2; que[mid].push(qi); } } } } for(int i = 0; i < Q; i++) que[ok[i]].push(i); fenwick_tree fw(N); fenwick_tree fw2(N); for(int i = 0; i < N; i++){ fw.add(i, -1); fw2.add(i, a[i]); } vector ans(Q); for(int i = 0; i < m; i++){ for(auto p : tb[i]){ fw2.add(p, -2 * a[p]); fw.add(p, 2); } while(!que[i].empty()){ auto qi = que[i].front(); que[i].pop(); auto [l, r] = query[qi]; ans[qi] = fw2.sum(l, r) + (ll)c[i] * fw.sum(l, r); } } for(auto &&v : ans) cout << v << '\n'; }