#include <bits/stdc++.h>
using namespace std;
int inline read() {
  int 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;
}
const int maxn = 200010;
int n, T, tot[maxn], ans;
struct Node {
  int m, p;
} a[maxn];
bool cmp(Node x, Node y) { return x.m > y.m; }
int main() {
  T = read();
  while (T--) {
    n = read();
    ans = 0;
    for (int i = 1; i <= n; i++) a[i].m = read(), a[i].p = read();
    sort(a + 1, a + n + 1, cmp);
    int cnt = 0, pl = 1;
    multiset<int> S;
    for (int i = n; i >= 1; i--) tot[a[i].m]++;
    for (int i = 1; i <= n; i++) tot[i] += tot[i - 1];
    for (int i = n; i >= 0; i--) {
      bool flag = 0;
      while (i <= a[pl].m && pl <= n) {
        S.insert(a[pl].p);
        pl++;
        flag = 1;
      }
      if (!flag) continue;
      if (tot[i - 1] + cnt < i) {
        int k = i - tot[i - 1] - cnt;
        for (int i = 1; i <= k; i++) {
          cnt++;
          ans += *S.begin();
          S.erase(S.begin());
        }
      }
    }
    printf("%d\n", ans);
    for (int i = 0; i <= n; i++) tot[i] = 0;
  }
  return 0;
}
