#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 {
  int p, m;
  node() {}
  node(int a, int b) { p = a, m = b; }
  bool operator<(const node& tmp) const {
    if (p == tmp.p)
      return m < tmp.m;
    else
      return p < tmp.p;
  }
} a[N];
int c[N];
void add(int pos, int x, int n) {
  while (pos <= n) {
    c[pos] += x;
    pos += (pos & -(pos));
  }
}
int sum(int pos) {
  int cnt = 0;
  while (pos) {
    cnt += c[pos];
    pos -= (pos & -(pos));
  }
  return cnt;
}
int main() {
  int T = read();
  while (T--) {
    int n = read();
    int must = 0;
    priority_queue<node> Q;
    long long int res = 0;
    for (int i = 1; i <= n; i++) c[i] = 0;
    for (int i = 1; i <= n; i++) {
      a[i].m = read(), a[i].p = read();
      if (a[i].m != 0) {
        res += a[i].p;
        Q.push(a[i]);
      } else {
        must++;
      }
    }
    while (Q.size()) {
      node x = Q.top();
      Q.pop();
      if (Q.size() + must + sum(Min(n, (int)Q.size() + must)) >= x.m) {
        add(x.m, 1, n);
        res -= x.p;
      } else
        must++;
    }
    printf("%lld\n", res);
  }
  return 0;
}
