import sys # sys.setrecursionlimit(200005) # sys.set_int_max_str_digits(200005) int1 = lambda x: int(x)-1 pDB = lambda *x: print(*x, end="\n", file=sys.stderr) p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr) def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def SI(): return sys.stdin.readline().rstrip() # dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] # dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] # inf = -1-(-1 << 31) inf = -1-(-1 << 62) md = 10**9+7 # md = 998244353 from bisect import bisect_left class WaveletMatrix: def __init__(self, aa): self._dec = sorted(set(aa)) self._enc = {a: i for i, a in enumerate(self._dec)} aa = [self._enc[a] for a in aa] self._log = len(self._dec).bit_length() self._n = len(aa) self._bb = [[0] for _ in range(self._log)] self._css = [[0] for _ in range(self._log)] for i in range(self._log)[::-1]: naa = [[], []] for a in aa: d = a >> i & 1 naa[d].append(a) self._bb[i].append(self._bb[i][-1]+d) if d==0:self._css[i].append(self._css[i][-1]+self._dec[a]) aa = naa[0] for a in naa[1]: aa.append(a) self._css[i].append(self._css[i][-1]+self._dec[a]) self._fi = {} # First index in last array for i in range(self._n)[::-1]: self._fi[aa[i]] = i self._aa = aa def _move(self, i, idx, d): if d: return self._n-self._bb[i][-1]+self._bb[i][idx] return idx-self._bb[i][idx] def __getitem__(self, idx): res = 0 for i in range(self._log)[::-1]: d = self._bb[i][idx+1]-self._bb[i][idx] res |= d << i idx = self._move(i, idx, d) return self._dec[res] # ith value in sorted [l,r) def quantile(self, l, r, ith): css=self._css sl=cl=sr=cr=0 for i in range(self._log)[::-1]: c0 = r-l-(self._bb[i][r]-self._bb[i][l]) nl, nr = self._move(i, l, 0), self._move(i, r, 0) l, r = self._move(i, l, 1), self._move(i, r, 1) if c0 > ith: l,r,nl,nr=nl,nr,l,r sr+=css[i][nr]-css[i][nl] cr+=nr-nl else: ith -= c0 sl+=css[i][nr]-css[i][nl] cl+=nr-nl return self._dec[self._aa[l]],cl,sl,cr,sr n,q=LI() aa=LI() wm=WaveletMatrix(aa) for _ in range(q): l,r=LI() l-=1 med,cl,sl,cr,sr=wm.quantile(l,r,(r-l)//2) ans=med*cl-sl+sr-med*cr print(ans)