#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7, INF = 1e9 + 1, mod = 1e9 + 7;
const double PI = 3.141592653589793238462643383279502884197, eps = 1e-9;
bool compare(pair<int, int> x, pair<int, int> y) {
  return x.first < y.first || (x.first == y.first && x.second > y.second);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t = 0;
  cin >> t;
  while (t--) {
    int n, cnt = 0;
    long long s = 0;
    cin >> n;
    pair<int, int> mp[n];
    vector<int> vec[n + 1], sol[n + 1];
    set<int> st;
    set<int>::iterator it;
    for (int i = 0; i < n; i++) {
      cin >> mp[i].second >> mp[i].first;
      vec[mp[i].second].push_back(mp[i].first);
    }
    for (int i = 0; i < n; i++) {
      sort(vec[i].begin(), vec[i].end());
      reverse(vec[i].begin(), vec[i].end());
    }
    sort(mp, mp + n, compare);
    for (int i = 0, j = 0; i < n; i++) {
      if (i) {
        for (int k : sol[i - 1]) st.insert(k);
        sol[i - 1].clear();
      }
      if (i <= cnt)
        cnt += vec[i].size();
      else {
        while (j < n && mp[j].second < i) j++;
        s += mp[j].first;
        vec[mp[j].second].pop_back();
        sol[mp[j].second].push_back(mp[j].first);
        j++, cnt++, i--;
        if (!st.empty()) {
          it = st.end();
          it--;
          s -= *it;
          st.erase(it);
        }
      }
    }
    cout << s << '\n';
  }
  return 0;
}
