#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
typedef struct voter {
  int m;
  int p;
} VOTER;
VOTER voters[MAXN];
int mFirstComp(const void *a, const void *b) {
  VOTER *Pt1 = (VOTER *)a;
  VOTER *Pt2 = (VOTER *)b;
  if (Pt1->m != Pt2->m)
    return (Pt1->m - Pt2->m);
  else
    return (Pt2->p - Pt1->p);
}
int main() {
  int t;
  int n;
  cin >> t;
  while (t--) {
    priority_queue<int, vector<int>, greater<int> > q;
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> voters[i].m >> voters[i].p;
    qsort(voters + 1, n, sizeof(VOTER), mFirstComp);
    long long curCoins = 0;
    for (int i = n; i > 0; --i) {
      int j = i;
      int m = voters[i].m;
      while (j && voters[j].m == m) {
        q.push(voters[j--].p);
      }
      if (q.size() >= n - m) {
        int delta = q.size() - (n - m);
        i = j + 1;
        for (int k = 0; k < delta; ++k) {
          int mins = q.top();
          curCoins += mins;
          q.pop();
        }
      }
    }
    cout << curCoins << endl;
  }
  return 0;
}
