#include <bits/stdc++.h>
using namespace std;
int n;
struct Can {
  int cost;
  int m;
  int ind;
};
bool operator<(Can x, Can y) {
  if (x.cost == y.cost && x.m == y.m) return x.ind < y.ind;
  if (x.cost == y.cost) return x.m > y.m;
  return x.cost < y.cost;
}
bool sorting(Can x, Can y) {
  if (x.m == y.m) return x.cost > y.cost;
  return x.m < y.m;
}
int t;
int main() {
  cin >> t;
  while (t--) {
    cin >> n;
    Can can[n];
    for (int i = 0; i < n; i++) cin >> can[i].m >> can[i].cost;
    sort(can, can + n, sorting);
    vector<Can> vec;
    for (int i = 0; i < n; i++) can[i].ind = i;
    multiset<Can> ms;
    for (int i = 0; i < n; i++) ms.insert(can[i]);
    int it = 0;
    long long ans = 0;
    bool v[n];
    for (int i = 0; i < n; i++) v[i] = false;
    int s = 0;
    while (s != n) {
      while (can[it].m <= s && s < n) {
        if (!v[it]) {
          s++;
          ms.erase(ms.find(can[it]));
        }
        v[it] = true;
        it++;
        if (it == n) break;
      }
      if (s != n) {
        Can c = *ms.begin();
        s++;
        ans += c.cost;
        v[c.ind] = true;
        ms.erase(ms.begin());
        vec.push_back(c);
      }
    }
    s = 0;
    sort(vec.begin(), vec.end(), sorting);
    reverse(vec.begin(), vec.end());
    for (int i = 0; i < n; i++) v[i] = false;
    it = 0;
    ans = 0;
    for (int i = 0; i < vec.size(); i++) {
      while (can[it].m <= s && it < n) {
        if (!v[it]) s++;
        v[it] = true;
        it++;
        if (it == n) break;
      }
      if (!v[vec[i].ind]) {
        ans += vec[i].cost;
        s++;
        v[vec[i].ind] = true;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
