#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    int n;
    cin >> n;
    vector<vector<int> > a(n);
    long long ans = 0;
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      a[m].push_back(p);
    }
    for (int i = 0; i < n; i++) sort(a[i].begin(), a[i].end());
    multiset<int> s;
    for (int i = n - 1, l = n; i > 0; i--) {
      s.insert(a[i].begin(), a[i].end());
      l -= a[i].size();
      for (int j = 0; j < a[i].size() && l < i; j++, l++, s.erase(s.begin()))
        ans += *s.begin();
    }
    cout << ans << endl;
  }
  return 0;
}
