#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int tt;
  cin >> tt;
  while (tt--) {
    int n;
    cin >> n;
    int m, p;
    vector<vector<int> > v(n);
    for (int i = 0; i < n; i++) {
      cin >> m >> p;
      v[m].push_back(p);
    }
    multiset<int> s;
    int pref = n, cnt = 0;
    long long int res = 0;
    for (int i = n - 1; i >= 0; i--) {
      pref -= v[i].size();
      int need = i - pref - cnt;
      for (auto x : v[i]) s.insert(x);
      while (need > 0) {
        cnt++;
        need--;
        res += *(s.begin());
        s.erase(s.begin());
      }
    }
    cout << res << endl;
  }
  return 0;
}
