#include #include #include #include #include #include #include #define llint long long using namespace std; typedef pair P; typedef pair Q; int n, Qnum, B; int a[200005]; vector qvec; llint ans[200005]; multiset head, tail; llint hsum, tsum; void adjust(llint m) { while((int)head.size() > (m+1)/2){ auto it = head.end(); it--; tsum += *it, hsum -= *it; tail.insert(*it), head.erase(it); } while((int)head.size() < (m+1)/2){ hsum += *tail.begin(), tsum -= *tail.begin(); head.insert(*tail.begin()), tail.erase(tail.begin()); } } void add(llint x) { llint m = head.size() + tail.size(); if(head.size() == 0) head.insert(x), hsum += x; else{ auto it = head.end(); it--; if(*it >= x) head.insert(x), hsum += x; else tail.insert(x), tsum += x; } m++; adjust(m); } void erase(llint x) { llint m = head.size() + tail.size(); if(head.count(x)) head.erase(head.lower_bound(x)), hsum -= x; else tail.erase(tail.lower_bound(x)), tsum -= x; m--; adjust(m); } llint get() { auto it = head.end(); it--; llint med = *it; llint ret = tsum - med * (llint)tail.size(); ret += med * (llint)head.size() - hsum; return ret; } int main(void) { //ios::sync_with_stdio(0); //cin.tie(0); //cin >> n >> Qnum; scanf("%d %d", &n, &Qnum); for(int i = 1; i <= n; i++) scanf("%d", &a[i]);//cin >> a[i]; B = sqrt(n); int l, r; for(int q = 1; q <= Qnum; q++){ //cin >> l >> r; scanf("%d %d", &l, &r); qvec.push_back(Q(P(l/B, r), P(l, q))); } sort(qvec.begin(), qvec.end()); l = qvec[0].second.first, r = qvec[0].first.second; for(int i = l; i <= r; i++) add(a[i]); ans[qvec[0].second.second] = get(); for(int i = 1; i < qvec.size(); i++){ llint nl = qvec[i].second.first, nr = qvec[i].first.second; while(l > nl) l--, add(a[l]); while(r < nr) r++, add(a[r]); while(l < nl) erase(a[l]), l++; while(r > nr) erase(a[r]), r--; llint qid = qvec[i].second.second; ans[qid] = get(); } for(int q = 1; q <= Qnum; q++) printf("%lld\n", ans[q]); //cout << ans[q] << "\n"; flush(cout); return 0; }