#include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
  puts(f ? "YES" : "NO");
  exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
  x += y;
  if (x >= mod) x -= mod;
}
void et() {
  puts("-1");
  exit(0);
}
int SZ;
struct mb {
  int l, r, id;
  void rd(int i) {
    scanf("%d%d", &l, &r);
    l--;
    r--;
    id = i;
  }
  bool operator<(const mb &o) const {
    if (l / SZ == o.l / SZ) {
      return (l / SZ) & 1 ? r > o.r : r < o.r;
    }
    return l / SZ < o.l / SZ;
  }
} q[100005];
int a[100005], cnt[100005], fre[100005], tfre[100005];
long long ans[100005];
vector<int> big;
void add(int val, int c) {
  fre[cnt[val]]--;
  cnt[val] += c;
  fre[cnt[val]]++;
}
void fmain() {
  scanf("%d", &n);
  for (int(i) = 0; (i) < (int)(n); (i)++) scanf("%d", a + i);
  SZ = sqrt(n) * max(1, (int)log(n));
  for (int(i) = 0; (i) < (int)(n); (i)++) {
    cnt[a[i]]++;
    if (cnt[a[i]] == SZ) big.push_back(a[i]);
  }
  memset(cnt, 0, sizeof cnt);
  scanf("%d", &m);
  for (int(i) = 1; (i) <= (int)(m); (i)++) q[i].rd(i);
  sort(q, q + m);
  int L = q[1].l, R = q[1].l - 1;
  for (int(i) = 1; (i) <= (int)(m); (i)++) {
    while (R < q[i].r) add(a[++R], 1);
    while (L > q[i].l) add(a[--L], 1);
    while (R > q[i].r) add(a[R--], -1);
    while (L < q[i].l) add(a[L++], -1);
    long long tmp = 0;
    priority_queue<int, std::vector<int>, std::greater<int>> qu;
    for (int b : big)
      if (cnt[b] >= SZ) qu.push(cnt[b]);
    int pre = -1;
    for (int(j) = 0; (j) < (int)(SZ); (j)++) tfre[j] = fre[j];
    for (int j = 1; j < SZ; j++)
      if (tfre[j] > 0) {
        if (pre != -1) {
          tmp += pre + j;
          tfre[j]--;
          if (pre + j < SZ)
            tfre[pre + j]++;
          else
            qu.push(pre + j);
          pre = -1;
        }
        if (tfre[j] & 1) {
          tfre[j]--;
          pre = j;
        }
        tmp += tfre[j] * j;
        if (j + j < SZ) {
          tfre[j + j] += tfre[j] / 2;
        } else {
          for (int(z) = 0; (z) < (int)(tfre[j] / 2); (z)++) qu.push(j + j);
        }
      }
    if (pre != -1) qu.push(pre);
    while (qu.size() > 1) {
      int x = qu.top();
      qu.pop();
      x += qu.top();
      qu.pop();
      tmp += x;
      qu.push(x);
    }
    ans[q[i].id] = tmp;
  }
  for (int(i) = 1; (i) <= (int)(m); (i)++) printf("%lld\n", ans[i]);
}
int main() {
  fmain();
  return 0;
}
