#include <bits/stdc++.h>
using namespace std;
void fun() {}
long long int __gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return __gcd(b, a % b);
}
long long int poww(long long int a, long long int b, long long int md) {
  if (b < 0) return 0;
  if (a == 0) return 0;
  long long int res = 1;
  while (b) {
    if (b & 1) {
      res = (1ll * res * a) % md;
    }
    a = (1ll * a * a) % md;
    b >>= 1;
  }
  return res;
}
long long int divide(long long int a, long long int b, long long int md) {
  long long int rr = a * (poww(b, md - 2, md));
  rr %= md;
  return rr;
}
const long long int size = 3e3 + 5;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  fun();
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    long long int prefix[n + 1];
    memset(prefix, 0, sizeof(prefix));
    vector<long long int> g[n + 1];
    for (long long int i = 1; i <= n; i++) {
      long long int m, p;
      cin >> m >> p;
      g[m].push_back(p);
      prefix[m]++;
    }
    for (long long int i = 1; i <= n; i++) {
      prefix[i] += prefix[i - 1];
    }
    long long int cnt = 0, ans = 0;
    priority_queue<long long int> pq;
    for (long long int i = n - 1; i >= 0; i--) {
      for (long long int ele : g[i]) {
        pq.push(-ele);
      }
      if ((i > 0 && prefix[i - 1] + cnt >= i) || cnt >= i) {
        continue;
      } else {
        long long int tobuy = i - cnt - prefix[i - 1];
        while (tobuy--) {
          ans += -pq.top();
          pq.pop();
          cnt++;
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
