#include <bits/stdc++.h>
using namespace std;
const long long ms = 2e5 + 1000;
long long n, m, t, p;
long long qtM[ms];
long long prefM[ms];
vector<long long> priceM[ms];
map<long long, long long> freq;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> t;
  while (t--) {
    cin >> n;
    for (long long i = 0; i < n; i++) {
      priceM[i].clear();
    }
    for (long long i = 0; i < n; i++) {
      cin >> m >> p;
      priceM[m].push_back(p);
    }
    long long ans = 0;
    long long left = n;
    long long used = 0;
    priority_queue<long long> bank;
    for (long long i = n - 1; i >= 0; i--) {
      for (auto p : priceM[i]) bank.push(-p);
      left -= priceM[i].size();
      long long necessary = i - left;
      long long k = 0;
      for (long long j = used; j < necessary && !bank.empty(); j++) {
        used++;
        ans += (-bank.top());
        bank.pop();
        k++;
      }
    }
    cout << ans << '\n';
  }
}
