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