#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 10;
struct V {
  int m, p;
} vt[N];
int n, x[N];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int T;
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 0; i < n; ++i) cin >> vt[i].m >> vt[i].p;
    sort(vt, vt + n, [](V& a, V& b) { return a.m < b.m; });
    memset(x, 0, sizeof(int) * n);
    for (int i = 0; i < n; ++i) {
      if (i && vt[i].m == vt[i - 1].m) continue;
      int d = vt[i].m - i;
      x[i] = d;
      if (d >= n - i) break;
    }
    ll ans = 0, c = 0;
    priority_queue<int> q;
    for (int i = n - 1; i >= 0; --i) {
      q.push(-vt[i].p);
      while (c < x[i] && q.size()) {
        int z = -q.top();
        q.pop();
        ans += z;
        ++c;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
