#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int tt;
  cin >> tt;
  while (tt--) {
    int n;
    cin >> n;
    vector<vector<int>> m(n, vector<int>());
    for (int i = 0; i < n; i++) {
      int mi, pi;
      cin >> mi >> pi;
      m[mi].push_back(pi);
    }
    vector<int> pref(n + 10);
    pref[0] = m[0].size();
    for (int i = 1; i < n; i++) {
      pref[i] = pref[i - 1] + m[i].size();
    }
    int bought = 0;
    long long cost = 0;
    priority_queue<int> q;
    for (int i = n - 1; i >= 1; i--) {
      for (auto e : m[i]) q.push(-e);
      int needed = i - bought - pref[i - 1];
      if (needed <= 0) continue;
      bought += needed;
      while (needed--) {
        cost += -q.top();
        q.pop();
      }
    }
    cout << cost << endl;
  }
  return 0;
}
