#include <bits/stdc++.h>
#pragma GCC optimize("-O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
const long long MAXN = 1123456;
const long long N = 2e6;
const long long inf = 3e18;
mt19937_64 rnd(chrono::system_clock::now().time_since_epoch().count());
template <typename T>
void vout(T s) {
  cout << s << endl;
  exit(0);
}
vector<long long> v[MAXN];
void sol() {
  long long n;
  cin >> n;
  vector<pair<long long, long long> > a(n);
  for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second;
  for (int i = 0; i < n; i++) swap(a[i].first, a[i].second);
  for (int i = 0; i <= n; i++) v[i].clear();
  for (int i = 0; i < n; i++) v[a[i].second].push_back(i);
  long long kol = n;
  long long ans = 0;
  multiset<long long> s;
  long long cnt = 0;
  for (int i = n - 1; i >= 0; i--) {
    for (auto j : v[i]) {
      kol--;
      s.insert(a[j].first);
    }
    if (kol + cnt >= i) {
      continue;
    } else {
      long long d = i - kol - cnt;
      while (d--) {
        cnt++;
        ans += *s.begin();
        s.erase(s.begin());
      }
    }
  }
  cout << ans << "\n";
}
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    sol();
  }
  return 0;
}
