#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int t, n;
vector<int> v[N];
int main() {
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
      v[i].clear();
    }
    for (int i = 0; i < n; i++) {
      int x, second;
      cin >> x >> second;
      v[x].push_back(second);
    }
    multiset<int> q;
    long long res = 0;
    int pref = n;
    int cnt = 0;
    for (int i = n - 1; i >= 0; i--) {
      pref -= v[i].size();
      int need = i - pref;
      for (auto x : v[i]) q.insert(x);
      while (cnt < need) {
        cnt++;
        res += *q.begin();
        q.erase(q.begin());
      }
    }
    cout << res << endl;
  }
  return 0;
}
