#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<long long> cnt(n, 0);
    vector<pair<long long, long long> > arr(n);
    for (long long i = 0; i < n; i++) {
      cin >> arr[i].first >> arr[i].second;
      cnt[arr[i].first]++;
    }
    for (long long i = 1; i < n; i++) cnt[i] += cnt[i - 1];
    sort(arr.begin(), arr.end());
    multiset<long long> s;
    long long ans = 0, j = n - 1, x, b = 0;
    for (long long i = n - 1; i > 0; i--) {
      while (j >= 0 && arr[j].first == i) {
        s.insert(arr[j].second);
        j--;
      }
      if (cnt[i - 1] < i) {
        x = max(0ll, i - cnt[i - 1] - b);
        while (x--) {
          auto p = s.begin();
          ans += *p;
          b++;
          s.erase(p);
        }
      }
    }
    cout << ans << "\n";
  }
}
