#include <bits/stdc++.h>
using namespace std;
inline int read() {
  char ch = getchar();
  int f = 1, x = 0;
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return f * x;
}
const int N = 200005;
int t, n, p[N];
vector<int> v[N];
signed main() {
  t = read();
  while (t--) {
    n = read();
    for (int i = 0; i < n; i++) v[i].clear();
    for (int i = 1; i <= n; i++) {
      v[read()].push_back(i);
      p[i] = read();
    }
    priority_queue<int, vector<int>, greater<int> > q;
    int f = n, cnt = 0;
    long long ans = 0;
    for (int i = n - 1; ~i; i--) {
      f -= v[i].size();
      for (int j : v[i]) q.push(p[j]);
      for (; cnt < i - f; cnt++) ans += q.top(), q.pop();
    }
    printf("%lld\n", ans);
  }
  return 0;
}
