#include <bits/stdc++.h>
using namespace std;
long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  while ('0' > ch || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while ('0' <= ch && ch <= '9') {
    x = (x << 1) + (x << 3) + ch - '0';
    ch = getchar();
  }
  return x * f;
}
long long n, f, ans;
struct zlk {
  long long x;
  bool operator<(zlk b) const { return x > b.x; }
} wyx;
priority_queue<zlk> Q;
struct node {
  long long x, y;
} q[200005];
bool cmpp(node a, node b) { return a.x > b.x; }
signed main() {
  long long t = read();
  while (t--) {
    while (!Q.empty()) Q.pop();
    n = read();
    for (long long i = 1; i <= n; i++) q[i].x = read(), q[i].y = read();
    sort(q + 1, q + n + 1, cmpp);
    f = 0;
    ans = 0;
    wyx.x = q[1].y;
    Q.push(wyx);
    q[n + 1].x = -23232;
    for (long long i = 2; i <= n + 1; i++) {
      if (q[i].x != q[i - 1].x) {
        while (q[i - 1].x - (n - i + 1) - f > 0) {
          ans += Q.top().x;
          Q.pop();
          f++;
        }
      }
      wyx.x = q[i].y;
      Q.push(wyx);
    }
    printf("%lld\n", ans);
  }
  return 0;
}
