#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int qq;
  cin >> qq;
  while (qq--) {
    int n;
    cin >> n;
    pair<int, int> p[n];
    vector<int> ve[n];
    for (auto &i : p)
      cin >> i.first >> i.second, ve[i.first].push_back(i.second);
    sort(p, p + n);
    int pref = n, cnt = 0;
    long long res = 0;
    multiset<int> ms;
    for (int i = n - 1; i >= 0; i--) {
      pref -= ve[i].size();
      for (auto j : ve[i]) ms.insert(j);
      while (pref + cnt < i) res += (*ms.begin()), ms.erase(ms.begin()), cnt++;
    }
    cout << res << "\n";
  }
  return 0;
}
