#include <bits/stdc++.h>
using namespace std;
void read() {
  long long n;
  cin >> n;
  vector<vector<long long> > cnt(n);
  for (long long i = 0; i < n; i++) {
    long long m, p;
    cin >> m >> p;
    cnt[m].push_back(p);
  }
  long long pref = n, buy = 0, ans = 0;
  multiset<long long> nb;
  for (long long i = n - 1; i >= 0; --i) {
    for (long long p = 0; p < (long long)(cnt[i].size()); p++)
      nb.insert(cnt[i][p]);
    pref -= (long long)(cnt[i].size());
    while (pref + buy < i) {
      ans += *(nb.begin());
      nb.erase(nb.begin());
      buy++;
    }
  }
  cout << ans << "\n";
}
void solve() {}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    read();
    solve();
  }
}
