#include <bits/stdc++.h>
using namespace std;
long long n;
pair<long long, long long> p[200009];
set<pair<long long, long long> > se;
bool done[200009];
void solve() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> p[i].first >> p[i].second;
  }
  sort(p, p + n);
  for (int i = 0; i < n; i++) {
    done[i] = 0;
    se.insert({p[i].second, i});
  }
  long long curr = 0, cnt = 0;
  for (int i = 0; i < n; i++) {
    bool z = 0;
    if (done[i]) continue;
    while (cnt < p[i].first) {
      if (i + 1 != n && p[i].first != p[i + 1].first)
        se.erase({p[i].second, i}), z = 1;
      long long x = se.begin()->first;
      long long id = se.begin()->second;
      done[id] = 1, curr += x, cnt++;
      se.erase(se.find({x, id}));
    }
    if (se.find({p[i].second, i}) != se.end())
      se.erase({p[i].second, i}), cnt++;
    if (z == 1) cnt++;
  }
  cout << curr << endl;
}
int main() {
  int t;
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cin >> t;
  while (t--) solve();
}
