#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long q;
  cin >> q;
  for (long long _ = (0); _ < ((q)); ++_) {
    long long n;
    cin >> n;
    vector<long long> a[n];
    for (long long i = (0); i < ((n)); ++i) {
      long long x, y;
      cin >> x >> y;
      a[x].push_back(y);
    }
    vector<long long> s(n, 0);
    for (long long i = (0); i < ((n)); ++i) s[i] = a[i].size();
    for (long long i = (0); i < ((n - 1)); ++i) s[i + 1] += s[i];
    vector<long long> tmp;
    long long ans = 0;
    for (long long i = ((n)-1); i >= (0); --i) {
      if (s[i] >= i + 1) {
        for (long long x : a[i]) tmp.push_back(x);
        continue;
      }
      sort(tmp.begin(), tmp.end());
      for (long long j = (0); j < (((i + 1) - s[i])); ++j) ans += tmp[j];
      break;
    }
    cout << ans << "\n";
  }
  return 0;
}
