#include <bits/stdc++.h>
using namespace std;
const int N = 1000010, mod = 1e9 + 7, INF = 0x3f3f3f3f;
const double eps = 1e-6;
int n;
vector<pair<int, int> > v;
vector<int> all, tp;
struct Node {
  int p, m;
  bool operator<(const Node &W) const { return m < W.m; }
} a[N];
int main() {
  int _;
  scanf("%d", &_);
  while (_--) {
    scanf("%d", &n);
    v.clear();
    all.clear();
    for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].m, &a[i].p);
    sort(a + 1, a + 1 + n);
    for (int i = 1; i <= n; i++) {
      int cnt = 0, st = i;
      int now = a[i].m;
      tp.clear();
      tp.push_back(a[i].p);
      i++;
      if (i <= n && a[i].m <= now) {
        while (i <= n && a[i].m <= now) tp.push_back(a[i].p), now++, i++;
        i--;
      }
      v.push_back({st, i});
      sort(tp.begin(), tp.end());
      for (int j = (int)tp.size() - 1; j >= 0; j--) all.push_back(tp[j]);
    }
    long long ans = 0;
    int sum = 0, st = 0;
    for (int i = 0; i < v.size();) {
      while (i < v.size() && sum >= a[v[i].first].m) {
        sum += v[i].second - v[i].first + 1, st += v[i].second - v[i].first + 1,
            i++;
      }
      if (st >= all.size()) break;
      sum++;
      ans += all.back();
      all.pop_back();
    }
    printf("%lld\n", ans);
  }
  return 0;
}
