#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 10;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t, n, m, p, c, k;
  long long ans;
  vector<vector<pair<int, int>>> T;
  vector<bool> U;
  vector<tuple<int, int, int>> A;
  multiset<int> B;
  cin >> t;
  for (int i = 0; i < t; i++) {
    cin >> n;
    T = vector<vector<pair<int, int>>>(n);
    U = vector<bool>(n);
    A = vector<tuple<int, int, int>>(n);
    B = multiset<int>();
    for (int j = 0; j < n; j++) {
      cin >> m >> p;
      T[m].push_back({j, p});
      A[j] = {p, m, j};
    }
    sort(A.begin(), A.end(), greater<tuple<int, int, int>>());
    c = 0;
    ans = 0;
    for (int j = 0; j < n; j++) {
      if (j > c) {
        while (get<1>(A.back()) < j) A.pop_back();
        tie(p, m, k) = A.back();
        A.pop_back();
        U[k] = true;
        ans += p;
        c++;
        if (B.size() > 0) {
          auto it = --B.end();
          ans -= *it;
          B.erase(it);
        }
      }
      for (pair<int, int> l : T[j]) {
        if (U[l.first])
          B.insert(l.second);
        else
          c++;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
