#include <bits/stdc++.h>
using namespace std;
const int maxn = 5000 + 10;
struct Node {
  int m;
  long long p;
  bool operator<(const Node& tmp) const {
    return m == tmp.m ? p > tmp.p : m < tmp.m;
  }
} node[maxn];
long long minv[maxn << 2];
void Build(int id, int L, int R) {
  if (L == R) {
    minv[id] = node[L].p;
    return;
  }
  Build(id << 1, L, ((L + R) >> 1));
  Build(id << 1 | 1, ((L + R) >> 1) + 1, R);
  minv[id] = min(minv[id << 1], minv[id << 1 | 1]);
}
void Update(int id, int L, int R, int pos, long long val) {
  if (L == R) {
    minv[id] = val;
    return;
  } else {
    if (pos <= ((L + R) >> 1))
      Update(id << 1, L, ((L + R) >> 1), pos, val);
    else
      Update(id << 1 | 1, ((L + R) >> 1) + 1, R, pos, val);
    minv[id] = min(minv[id << 1], minv[id << 1 | 1]);
    int a;
  }
}
long long Query(int id, int L, int R, int l, int r, int& pos) {
  if (l > r) return LONG_LONG_MAX;
  if (L == R) {
    pos = L;
    return minv[id];
  } else {
    int pos1, pos2;
    if (r <= ((L + R) >> 1)) {
      long long res1 = Query(id << 1, L, ((L + R) >> 1), l, r, pos1);
      pos = pos1;
      return res1;
    } else if (l >= ((L + R) >> 1) + 1) {
      long long res2 = Query(id << 1 | 1, ((L + R) >> 1) + 1, R, l, r, pos2);
      pos = pos2;
      return res2;
    } else {
      long long res1 = Query(id << 1, L, ((L + R) >> 1), l, r, pos1);
      long long res2 = Query(id << 1 | 1, ((L + R) >> 1) + 1, R, l, r, pos2);
      if (res1 <= res2) {
        pos = pos1;
        return res1;
      } else {
        pos = pos2;
        return res2;
      }
    }
  }
}
int vis[maxn];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    memset(vis, 0, sizeof(int) * (n + 5));
    for (int i = 1; i <= n; i++) {
      int m;
      long long p;
      scanf("%d%lld", &m, &p);
      node[i] = {m, p};
    }
    sort(node + 1, node + 1 + n);
    Build(1, 1, n);
    int cnt = 0;
    long long ans = 0;
    for (int i = 1; i < n; i++) {
      if (vis[i]) continue;
      if (node[i].m >= i + cnt) {
        int tmp = node[i].m;
        int j = i;
        for (; j <= n; j++) {
          if (node[j].m > j - i + node[i].m) break;
        }
        cnt += tmp;
        tmp = node[i].m - (i - 1);
        while (tmp--) {
          int pos;
          long long tmpp = Query(1, 1, n, j, n, pos);
          if (tmpp == LONG_LONG_MAX) {
            ans += Query(1, 1, n, i + 1, n, pos);
            Update(1, 1, n, pos, LONG_LONG_MAX);
            vis[pos] = 1;
            int tmppp;
          } else {
            ans += tmpp;
            Update(1, 1, n, pos, LONG_LONG_MAX);
            vis[pos] = 1;
          }
        }
      }
    }
    printf("%lld\n", ans);
  }
  getchar();
  getchar();
  return 0;
}
