#include <bits/stdc++.h>
#pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
using namespace std;
void solve() {
  int n;
  cin >> n;
  vector<int> amt(n + 1);
  map<int, vector<long long>> mp;
  for (int i = 0; i < n; ++i) {
    int m, p;
    cin >> m >> p;
    amt[m]++;
    mp[m].push_back(p);
  }
  for (int i = 0; i < n - 1; ++i) {
    amt[i + 1] += amt[i];
  }
  priority_queue<long long, vector<long long>, greater<long long>> Q;
  int cnt = 0;
  long long res = 0;
  auto it = mp.rbegin();
  for (; it != mp.rend(); ++it) {
    int m = it->first;
    auto arr = it->second;
    for (auto x : arr) {
      Q.push(x);
    }
    int need = m - amt[m] + arr.size() - cnt;
    if (need > 0) {
      while (need--) {
        res += Q.top();
        Q.pop();
        ++cnt;
      }
    }
  }
  cout << res << endl;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    solve();
  }
}
