#include <bits/stdc++.h>
using namespace std;
const int N = 200002 + 1;
const int MOD = 1000000007;
const long long MAX = 10000000000;
const int oo = 1e9;
int t, n;
struct person {
  int p, m, idx;
  bool operator<(const person &rhs) const {
    if (m != rhs.m) return m < rhs.m;
    if (p != rhs.p) return p > rhs.p;
    return idx < rhs.idx;
  }
};
person p[N], og[N];
int main() {
  cin >> t;
  while (t--) {
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
      scanf("%d%d", &p[i].m, &p[i].p);
      p[i].idx = i;
      og[i] = p[i];
    }
    sort(p, p + n);
    for (int i = 0; i < n; ++i) {
      p[i].idx = i;
      og[i] = p[i];
      ;
    }
    set<person> ab;
    set<pair<int, int> > highest;
    for (int i = 0; i < n; ++i) {
      if (p[i].m == 0) continue;
      ab.insert(p[i]);
      highest.insert(make_pair(p[i].p, p[i].idx));
      if (i >= p[i].m) {
        pair<int, int> hs = (*--highest.end());
        highest.erase(hs);
        ab.erase(og[hs.second]);
      }
      while (((int)ab.size()) - 1 >= (*ab.begin()).m) {
        person pp = *ab.begin();
        highest.erase(make_pair(pp.p, pp.idx));
        ab.erase(pp);
      }
    }
    long long ans = 0;
    for (auto v : ab) {
      ans += v.p;
    }
    printf("%lld\n", ans);
  }
  return 0;
}
