#include <bits/stdc++.h>
using namespace std;
const long long int MOD = 1e9 + 7, INF = 1e18;
template <class T>
inline T Min(const T& a, const T& b) {
  return a < b ? a : b;
}
template <class T>
inline T Max(const T& a, const T& b) {
  return a < b ? b : a;
}
inline int read() {
  char ch = getchar();
  int x = 0, f = 1;
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while ('0' <= ch && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
inline long long int readl() {
  char ch = getchar();
  long long int x = 0, f = 1;
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while ('0' <= ch && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
inline long long int ksm(long long int a, long long int b) {
  long long int res = 1;
  while (b) {
    if (b & 1) res = res * a % MOD;
    a = a * a % MOD;
    b >>= 1;
  }
  return res;
}
inline long long int ksc(long long int a, long long int b) {
  long long int res = 0;
  while (b) {
    if (b & 1) res = res + a >= MOD ? res + a - MOD : res + a;
    a = a + a >= MOD ? a + a - MOD : a + a;
    b >>= 1;
  }
  return res;
}
const int N = 1e6 + 7;
struct node {
  long long int p, m;
  bool operator<(const node& tmp) const { return p > tmp.p; }
} a[N];
bool cmp(node a, node b) { return a.m < b.m; }
int main() {
  int T = read();
  while (T--) {
    int n = read();
    int must = 0;
    priority_queue<node> Q;
    for (int i = 1; i <= n; i++) {
      a[i].m = read(), a[i].p = read();
    }
    long long int res = 0;
    sort(a + 1, a + 1 + n, cmp);
    for (int i = n, j; i >= 1; i = j) {
      j = i;
      while (j >= 1 && a[j].m == a[i].m) Q.push(a[j--]);
      while (n - a[i].m < Q.size()) {
        res += Q.top().p;
        Q.pop();
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
