#include <bits/stdc++.h>
#pragma GCC optimize "O3"
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const int N = 2e5 + 5;
int n;
pair<int, int> t[N];
int ile[N], nowe[N];
vector<int> vals;
void solve() {
  cin >> n;
  for (int i = 1; i <= n; i++)
    cin >> t[i].second >> t[i].first, ile[t[i].second]++,
        vals.push_back(t[i].second);
  sort(vals.begin(), vals.end());
  vals.erase(unique(vals.begin(), vals.end()), vals.end());
  int suma = 0, akt = 0;
  for (auto &x : vals) {
    if (suma < x) akt = x;
    nowe[x] = akt;
    suma += ile[x];
  }
  for (int i = 1; i <= n; i++) t[i].second = nowe[t[i].second];
  sort(t + 1, t + n + 1, greater<pair<int, int> >());
  long long ans = 0;
  int kup = 0;
  for (int i = 1; i <= n; i++) {
    int pozost = kup + n - i;
    if (pozost < t[i].second) {
      ans += t[i].first;
      kup++;
    }
  }
  cout << ans << '\n';
  for (auto &x : vals) ile[x] = nowe[x] = 0;
  vals.clear();
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int tt;
  cin >> tt;
  for (int te = 1; te <= tt; te++) solve();
  return 0;
}
