#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long t;
  cin >> t;
  while (t--) {
    multiset<long long> sss;
    long long n;
    cin >> n;
    vector<long long> count(n, 0);
    vector<vector<long long>> mas(n);
    for (long long i = 0; i < n; i++) {
      long long mi, pi;
      cin >> mi >> pi;
      if (mi + 1 < n) count[mi + 1]++;
      mas[mi].push_back(pi);
    }
    for (long long i = 1; i < n; i++) {
      count[i] += count[i - 1];
    }
    for (long long i = 0; i < n; i++) {
      count[i] -= i;
    }
    long long ans = 0, tec = 0;
    for (long long i = n - 1; i >= 0; i--) {
      for (long long x : mas[i]) {
        sss.insert(x);
      }
      while (0 > count[i] + tec) {
        ans += *sss.begin();
        sss.erase(sss.begin());
        tec += 1;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
