#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long num = 0, neg = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') neg = -1;
    c = getchar();
  }
  while (isdigit(c)) {
    num = (num << 3) + (num << 1) + c - '0';
    c = getchar();
  }
  return num * neg;
}
struct node {
  long long m, p;
  bool operator<(const node &a) const { return p > a.p; }
} voter[200010];
priority_queue<node> line;
bool cmp1(node x, node y) { return x.m > y.m; }
long long T, n, sum[200010];
int main() {
  T = read();
  while (T--) {
    n = read();
    for (int i = 0; i <= n; ++i) sum[i] = 0;
    for (int i = 1; i <= n; ++i) {
      voter[i].m = read(), voter[i].p = read();
      ++sum[voter[i].m];
    }
    sort(voter + 1, voter + n + 1, cmp1);
    for (int i = 1; i <= n; ++i) sum[i] += sum[i - 1];
    long long i, cnt = 0, ans = 0, lmt, need;
    for (i = 1; i <= n; i) {
      lmt = voter[i].m;
      if (lmt == 0) break;
      while (voter[i].m == lmt && i <= n) line.push(voter[i++]);
      need = lmt - sum[lmt - 1] - cnt;
      while (need > 0 && !line.empty()) {
        ans += (line.top()).p;
        line.pop();
        ++cnt;
        --need;
      }
    }
    while (!line.empty()) line.pop();
    cout << ans << endl;
  }
  return 0;
}
