#include <bits/stdc++.h>
using namespace std;
void add(map<long long int, long long int>& m, long long int x,
         long long int cnt = 1) {
  auto jt = m.find(x);
  if (jt == m.end())
    m.insert({x, cnt});
  else
    jt->second += cnt;
}
void del(map<long long int, long long int>& m, long long int x,
         long long int cnt = 1) {
  auto jt = m.find(x);
  if (jt->second <= cnt)
    m.erase(jt);
  else
    jt->second -= cnt;
}
void fastIO() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  return;
}
int main() {
  fastIO();
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    long long int ans = 0;
    map<long long int, vector<long long int> > mp;
    for (int i = 0; i < n; i++) {
      long long int m, p;
      cin >> m >> p;
      if (mp.find(m) == mp.end()) {
        mp[m] = vector<long long int>(0, 0);
      }
      mp[m].push_back(p);
    }
    vector<long long int> prev;
    long long int cnt = 0;
    for (auto it = mp.begin(); it != mp.end(); it++) {
      prev.push_back(cnt);
      sort(it->second.begin(), it->second.end());
      cnt += it->second.size();
    }
    multiset<long long int> upper;
    int idx = prev.size() - 1;
    int taken = 0;
    for (auto it = mp.rbegin(); it != mp.rend(); it++) {
      long long int m = it->first;
      vector<long long int> curr = it->second;
      for (int i = 0; i < curr.size(); i++) upper.insert(curr[i]);
      while (prev[idx] + taken < m) {
        ans += *(upper.begin());
        upper.erase(upper.begin());
        taken++;
      }
      idx--;
    }
    cout << ans << endl;
  }
  return 0;
}
