#include <bits/stdc++.h>
using namespace std;
const int TSIZE = 1 << 19;
const int TSTART = TSIZE / 2 - 1;
pair<int, int> T[TSIZE];
int getv(int l, int r) {
  l += TSTART;
  r += TSTART;
  pair<int, int> res = pair<int, int>(10000000, -1);
  while (l < r) {
    res = min(res, T[l]);
    res = min(res, T[r]);
    l = (l - 1) / 2;
    r = (r - 1) / 2;
  }
  if (l == r) res = min(res, T[l]);
  return res.second;
}
void setv(int x, int v) {
  x += TSTART;
  T[x].first = v;
  while (x > 0) {
    x = (x - 1) / 2;
    T[x] = min(T[x * 2 + 1], T[x * 2 + 2]);
  }
}
bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
  if (a.first != b.first) {
    return a.first > b.first;
  }
  return a.second < b.second;
}
void solve() {
  int n;
  scanf("%d", &n);
  vector<pair<int, int>> a(n);
  vector<char> used(n);
  for (int i = 0; i < n; ++i) {
    scanf("%d%d", &a[i].first, &a[i].second);
  }
  sort(a.begin(), a.end(), cmp);
  for (int i = 0; i < n; ++i) {
    T[i + TSTART].second = i;
    T[i + TSTART].first = a[i].second;
  }
  for (int x = n + TSTART; x < TSIZE; ++x) {
    T[x].second = -1;
    T[x].first = 1 << 30;
  }
  for (int x = TSTART - 1; x >= 0; --x) {
    T[x] = min(T[2 * x + 1], T[2 * x + 2]);
  }
  long long r = 0;
  int j = n;
  int have = 0;
  for (int i = 0; i < n; ++i) {
    while (j > 0 && a[j - 1].first <= have) {
      --j;
      used[j] = 1;
      setv(j, 1 << 30);
      ++have;
    }
    if (have >= n) break;
    int idx = getv(0, j - 1);
    r += a[idx].second;
    used[idx] = 1;
    setv(idx, 1 << 30);
    ++have;
  }
  printf("%I64d\n", r);
}
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) solve();
  return 0;
}
