#include <bits/stdc++.h>
#pragma GCC optimize("-O3", "unroll-loops")
using namespace std;
template <typename T1, typename T2>
inline void chmin(T1& a, T2 b) {
  if (a > b) a = b;
}
template <typename T1, typename T2>
inline void chmax(T1& a, T2 b) {
  if (a < b) a = b;
}
const long long MOD = 1e9 + 7;
void solve() {
  long long N;
  cin >> N;
  vector<vector<long long>> v(N + 1);
  vector<long long> cum(N + 1);
  for (long long i = 0; i < N; i++) {
    long long n, a;
    cin >> n >> a;
    v[n].push_back(a);
    cum[n]++;
  }
  for (long long i = 0; i < N; i++) {
    cum[i + 1] += cum[i];
  }
  priority_queue<long long, vector<long long>, greater<long long>> que;
  long long cnt = 0;
  long long ans = 0;
  for (long long i = N - 1; i >= 1; i--) {
    long long pos = v[i].size();
    if (pos == 0) continue;
    for (long long j = 0; j < pos; j++) {
      que.push(v[i][j]);
    }
    long long rem = i - (cum[i - 1] + cnt);
    if (rem > 0) {
      for (long long j = 0; j < rem; j++) {
        ans += que.top();
        cnt++;
        que.pop();
      }
    }
  }
  cout << ans << '\n';
  ;
}
signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long long q;
  cin >> q;
  while (q--) solve();
}
