#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
void solve() {
  int N;
  cin >> N;
  vector<long long> P(N), M(N);
  for (int i = 0; i < (N); ++i) cin >> M[i] >> P[i];
  vector<vector<int>> v(N + 1);
  for (int i = 0; i < (N); ++i) v[M[i]].push_back(i);
  long long ans = 0;
  set<pair<long long, int>> se;
  int sum = 0;
  int rest = N;
  for (int i = N - 1; i >= 0; i--) {
    if (v[i].size() == 0) continue;
    rest -= v[i].size();
    for (int j = 0; j < v[i].size(); j++)
      se.insert(make_pair(P[v[i][j]], v[i][j]));
    if (sum + rest >= i) {
    } else {
      while (sum + rest < i) {
        auto itr = se.begin();
        int tar = (*itr).second;
        ans += P[tar];
        sum++;
        se.erase(itr);
      }
    }
  }
  cout << ans << endl;
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int T;
  cin >> T;
  for (int i = 0; i < (T); ++i) solve();
  return 0;
}
