#include int ri() { int n; scanf("%d", &n); return n; } struct SegTree { int n; std::vector data; std::vector sum; std::vector decomp; SegTree (int n_, const std::vector &decomp) : decomp(decomp) { for (n = 1; n < n_; n <<= 1); data.resize(2 * n); sum.resize(2 * n); } void add(int i, int val) { int64_t real = (int64_t) val * decomp[i]; for (i += n; i; i >>= 1) data[i] += val, sum[i] += real; } int64_t get_sum(int l, int r) { int64_t res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (r & 1) res += sum[--r]; if (l & 1) res += sum[l++]; } return res; } int median() { int cur = 1, l = 0, r = n; int n = data[1] >> 1; for (; r - l > 1; ) { int m = l + ((r - l) >> 1); if (n < data[cur << 1]) r = m, cur = cur << 1; else n -= data[cur << 1], l = m, cur = cur << 1 | 1; } return l; } }; int main() { int n = ri(), q = ri(); int a[n]; std::set as; for (int i = 0; i < n; i++) a[i] = ri(), as.insert(a[i]); std::map comp; std::vector decomp; int cnt = 0; for (auto i : as) comp[i] = cnt++, decomp.push_back(i); for (auto &i : a) i = comp[i]; int sq = sqrt(q); std::vector > > qs(sq + 2); std::vector ll(q), rr(q); for (int i = 0; i < q; i++) { int l = ri() - 1, r = ri(); ll[i] = l; rr[i] = r; qs[l / sq].push_back({l, r}); } std::map, int64_t> res; for (auto &i : qs) { if (!i.size()) continue; std::sort(i.begin(), i.end(), [](auto l, auto r) { return l.second < r.second; }); SegTree tree(cnt, decomp); int l = 0, r = 0; for (auto &j : i) { while (r < j.second) tree.add(a[r++], 1); while (l < j.first) tree.add(a[l++], -1); while (l > j.first) tree.add(a[--l], 1); int med = tree.median(); int med_real = decomp[med]; int before = tree.data[1] >> 1; int after = tree.data[1] - before; int64_t asn = tree.get_sum(med, tree.n) + (int64_t) med_real * (before - after) - tree.get_sum(0, med); res[j] = asn; } } for (int i = 0; i < q; i++) std::cout << res[{ll[i], rr[i]}] << std::endl; return 0; }