#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n;
  cin >> n;
  vector<vector<long long>> a(n);
  for (long long i = 0; i < n; i++) {
    long long m, p;
    cin >> m >> p;
    a[m].push_back(p);
  }
  for (auto &t : a) {
    sort(t.begin(), t.end());
  }
  vector<long long> pref(n + 1);
  for (long long i = 0; i < n; i++) {
    pref[i + 1] = pref[i] + a[i].size();
  }
  long long cnt = 0;
  long long ans = 0;
  multiset<long long> hv;
  for (long long i = n - 1; i >= 0; i--) {
    for (auto t : a[i]) {
      hv.insert(t);
    }
    long long to =
        min((long long)hv.size(), max((long long)0, i - cnt - pref[i]));
    for (long long j = 0; j < to; j++) {
      ans += *hv.begin();
      cnt++;
      hv.erase(hv.begin());
    }
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long q;
  cin >> q;
  while (q--) {
    solve();
  }
}
