#include <bits/stdc++.h>
using namespace std;
pair<int, int> in[200005];
int p[200005];
void solve() {
  int n;
  scanf("%d ", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d %d ", &in[i].first, &in[i].second);
  }
  sort(in, in + n);
  int num = 0;
  priority_queue<int, vector<int>, greater<int> > pq;
  long long ret = 0;
  for (int i = n - 1; i >= 0;) {
    if (i + 1 + num < in[i].first) {
      assert(i + 1 + num + pq.size() >= in[i].first);
      while (i + 1 + num < in[i].first) {
        ++num;
        ret += pq.top();
        pq.pop();
      }
    }
    int j;
    for (j = i; j >= 0; --j) {
      if (in[j].first != in[i].first) {
        break;
      }
      pq.push(in[j].second);
    }
    while (j + 1 + num < in[i].first) {
      ret += pq.top();
      pq.pop();
      ++num;
    }
    i = j;
  }
  printf("%lld\n", ret);
}
int main() {
  int T;
  scanf("%d ", &T);
  while (T--) {
    solve();
  }
  return 0;
}
