#include <bits/stdc++.h>
using namespace std;
template <class T>
bool inline rmn(T &a, T b) {
  return a > b ? (a = b, true) : false;
}
template <class T>
bool inline rmx(T &a, T b) {
  return a < b ? (a = b, true) : false;
}
const long long INFLL = 0x7f7f7f7f7f7f7f7f, MOD = 1e9 + 7;
const long long INF = 0x7f7f7f7f;
vector<vector<long long>> adj;
vector<long long> vis, color;
long long dx8[] = {0, 1, 1, 1, 0, -1, -1, -1},
          dy8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dx4[] = {0, 1, 0, -1},
          dy4[] = {1, 0, -1, 0};
inline long long mexp(long long x, long long n, long long m = MOD) {
  long long res = 1;
  x %= m;
  while (n) {
    if (n & 1) res = (res * x) % m;
    n >>= 1;
    x = (x * x) % m;
  }
  return res;
}
inline long long gcd(long long a, long long b) {
  if (a < 0) a = -a;
  if (b < 0) b = -b;
  while (a > 0 && b > 0) {
    if (a > b)
      a %= b;
    else
      b %= a;
  }
  return a + b;
}
int32_t main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout << fixed;
  cerr << fixed;
  cout << setprecision(10);
  cerr << setprecision(3);
  mt19937 genr(chrono::high_resolution_clock::now().time_since_epoch().count());
  long long T;
  for (cin >> T; T; T--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long>> v(n);
    for (long long i = 0; i < n; ++i) cin >> v[i].first >> v[i].second;
    sort(v.begin(), v.end());
    multiset<long long> m;
    long long ans = 0;
    for (long long i = n - 1, pref = n, cnt = 0; i >= 0;) {
      long long j = i - 1;
      m.insert(v[i].second);
      while (j >= 0 && v[j].first == v[i].first) {
        m.insert(v[j].second);
        --j;
      }
      pref -= i - j;
      while (pref + cnt < v[i].first) {
        ans += *m.begin();
        ++cnt;
        m.erase(m.begin());
      }
      i = j;
    }
    cout << ans << '\n';
  }
  return 0;
}
