#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
const long long MOD = 998244353;
const long long INF = 0x3f3f3f3f;
long long read() {
  long long x = 0, f = 1;
  char ch;
  do {
    ch = getchar();
    if (ch == '-') f = -1;
  } while (ch < '0' || ch > '9');
  do {
    x = x * 10 + ch - 48;
    ch = getchar();
  } while (ch >= '0' && ch <= '9');
  return x * f;
}
int N, M;
priority_queue<int, vector<int>, greater<int> > pq;
pair<int, int> a[MAXN];
void init() {
  while (!pq.empty()) {
    pq.pop();
  }
  a[0].first = -1;
  a[0].second = INF;
  sort(a + 1, a + 1 + N);
}
void solve() {
  int cnt;
  long long ans;
  scanf("%d", &N);
  for (int i = 1; i <= N; i++) {
    a[i].first = read();
    a[i].second = read();
  }
  init();
  ans = 0;
  cnt = 0;
  for (int i = N; i >= 1; i--) {
    while (a[i - 1].first == a[i].first) {
      pq.push(a[i].second);
      i--;
    }
    pq.push(a[i].second);
    if (a[i].first - cnt >= i) {
      for (int j = 0; j <= a[i].first - cnt - i; j++) {
        ans += pq.top();
        pq.pop();
      }
      cnt = a[i].first - i + 1;
    }
  }
  printf("%lld\n", ans);
}
int main() {
  int T;
  T = 1;
  scanf("%d", &T);
  while (T--) {
    solve();
  }
  return 0;
}
