#include <bits/stdc++.h>
using namespace std;
using LL = long long;
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int cas;
  cin >> cas;
  while (cas--) {
    int n;
    cin >> n;
    tuple<int, int, int> a[n];
    for (int i = 0, m, p; i < n; ++i) {
      cin >> m >> p;
      a[i] = {m, p, i + 1};
    };
    sort(a, a + n, [](tuple<int, int, int> &x, tuple<int, int, int> &y) {
      if (get<0>(x) == get<0>(y)) return get<1>(x) > get<1>(y);
      return get<0>(x) < get<0>(y);
    });
    LL r = 0;
    int now = 0;
    for (int i = n - 1; i >= 0; --i) {
      int id = lower_bound(a, a + i, make_tuple(get<0>(a[i]), 0, 0)) - a;
      if (id + (n - 1 - i) < get<0>(a[i])) {
        r += get<1>(a[i]);
        get<2>(a[i]) = 0;
        ++now;
      }
    }
    now = get<0>(a[0]) - now;
    if (now) {
      sort(a, a + n, [](tuple<int, int, int> &x, tuple<int, int, int> &y) {
        if (get<1>(x) == get<1>(y)) return get<0>(x) > get<0>(y);
        return get<1>(x) < get<1>(y);
      });
      for (int i = 0; i < n; ++i) {
        if (get<2>(a[i]) == 0) continue;
        r += get<1>(a[i]);
        if (--now == 0) break;
      }
    }
    cout << r << endl;
  }
  return 0;
}
