#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<multiset<long long>> m(n);
    multiset<pair<long long, int>> s;
    for (int i = 0; i < n; ++i) {
      int x;
      long long p;
      cin >> x >> p;
      m[x].insert(p);
    }
    int pref = n, cnt = 0;
    long long ans = 0;
    for (int i = n - 1; i >= 0; --i) {
      pref -= m[i].size();
      for (auto p : m[i]) s.insert({p, i});
      while (pref + cnt < i) {
        ans += s.begin()->first;
        s.erase(s.begin());
        ++cnt;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
