#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 7, N = 2e5 + 7;
vector<long long> G[N];
void solve() {
  long long n;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    long long m, p;
    cin >> m >> p;
    G[m].push_back(p);
  }
  long long pre = n, cnt = 0, ans = 0;
  multiset<long long> s;
  for (long long i = n - 1; i >= 0; i--) {
    if (G[i].empty()) continue;
    pre -= G[i].size();
    long long need = i - pre - cnt;
    for (long long j : G[i]) s.insert(j);
    while (need > cnt) {
      ans += *s.begin();
      s.erase(s.begin());
      cnt++;
    }
  }
  cout << ans << endl;
  for (long long i = 0; i < n; i++) G[i].clear();
}
signed main() {
  std::ios::sync_with_stdio(0);
  std::cin.tie(0);
  ;
  long long t;
  cin >> t;
  while (t--) solve();
}
