#include <bits/stdc++.h>
using namespace std;
int n, m, p, q, t, i, j, k, x, y, z, c, d, l, r, l1, l2, lst, a, b, mn, mx, cnt,
    cur, u, v, w;
vector<int> ord[200001];
int main() {
  cin >> t;
  while (t--) {
    multiset<int> ps;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
      ord[i].clear();
    }
    for (i = 0; i < n; i++) {
      scanf("%d%d", &m, &p);
      ord[m].push_back(p);
    }
    long long ans = 0;
    int pref = n;
    int cnt = 0;
    for (i = n - 1; i >= 0; i--) {
      pref -= ord[i].size();
      for (auto p : ord[i]) {
        ps.insert(p);
      }
      x = i;
      if (pref + cnt < x) {
        int need = x - pref - cnt;
        while (need--) {
          cnt++;
          ans += *ps.begin();
          ps.erase(ps.begin());
        }
      }
    }
    printf("%lld\n", ans);
  }
}
