#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n;
  cin >> n;
  pair<long long, long long> a[n];
  for (long long i = 0; i < n; ++i) cin >> a[i].second >> a[i].first;
  vector<long long> cnt(n);
  for (long long i = 0; i < n; ++i) ++cnt[a[i].second];
  sort(a, a + n);
  long long l = -1, r = n;
  while (l < r - 1) {
    long long m = (l + r) / 2;
    long long vt = m;
    for (long long i = 0; i < m; ++i) --cnt[a[i].second];
    for (long long i = 0; i < n; ++i) {
      if (vt >= i)
        vt += cnt[i];
      else if (cnt[i])
        break;
    }
    if (vt == n)
      r = m;
    else
      l = m;
    for (long long i = 0; i < m; ++i) ++cnt[a[i].second];
  }
  long long ans = 0;
  long long vt = 0, id = 0, buf = 0;
  for (long long i = 0; i < n; ++i) {
    if (vt >= i)
      vt += cnt[i];
    else if (cnt[i] && !(cnt[i] == 1 && i == vt + 1)) {
      while (vt < i) {
        if (vt == i - 1) {
          vt += buf;
          buf = 0;
          if (vt >= i) break;
        }
        while (a[id].second < i) ++id;
        ans += a[id].first;
        --cnt[a[id].second];
        ++vt;
        ++id;
      }
      vt += cnt[i];
    } else if (cnt[i])
      ++buf;
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t) {
    --t;
    solve();
  }
  return 0;
}
