#include <bits/stdc++.h>
using namespace std;
long long t, n;
pair<long long, long long> a[200009];
long long need[200009];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> t;
  while (t--) {
    cin >> n;
    for (long long i = 0; i < n; ++i) cin >> a[i].first >> a[i].second;
    sort(a, a + n);
    vector<int> tmp;
    for (long long i = 0; i < n; ++i) {
      if (i == 0 || a[i].first != a[i - 1].first) {
        need[a[i].first] = max((long long)0, a[i].first - i);
        tmp.push_back(a[i].first);
      }
    }
    long long sums = 0;
    multiset<long long> s;
    long long ans = 0;
    for (long long i = n - 1; i >= 0; --i) {
      s.insert(a[i].second);
      if (i == 0 || a[i].first != a[i - 1].first) {
        need[a[i].first] -= sums;
        while (need[a[i].first]-- && s.size() > 0) {
          ans += *s.begin();
          s.erase(s.begin());
          ++sums;
        }
      }
    }
    cout << ans << "\n";
  }
}
