#include <bits/stdc++.h>
using namespace std;
long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int T, n;
int b[200005];
struct data {
  int m, p;
} a[200005];
bool cmp(data x, data y) {
  if (x.m == y.m) return x.p > y.p;
  return x.m < y.m;
}
multiset<int> st;
int main() {
  T = read();
  while (T--) {
    n = read();
    for (int i = 1; i <= n; i++) a[i].m = read(), a[i].p = read();
    sort(a + 1, a + n + 1, cmp);
    st.clear();
    st.insert(0);
    for (int i = 1; i <= n; i++) b[i] = max(0, a[i].m - i + 1);
    int cnt = 0;
    long long ans = 0;
    for (int i = n; i >= 1; i--) {
      st.insert(a[i].p);
      while (cnt < b[i]) {
        int tmp = *st.upper_bound(0);
        st.erase(st.upper_bound(0));
        ans += tmp;
        cnt++;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
