#include <bits/stdc++.h>
using namespace std;
const long long tam = 510000;
const long long MOD = 1e9 + 7;
const long long MOD1 = 988244535;
const double EPS = 1e-9;
const double PI = acos(-1);
pair<long long, long long> v[tam];
long long dp[tam], need[tam];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long casos, n;
  cin >> casos;
  while (casos--) {
    cin >> n;
    for (long long i = 0; i < n; i++) {
      cin >> v[i].first >> v[i].second;
    }
    sort(v, v + n);
    long long ant = 0;
    for (long long i = 0; i < n; i++) {
      if (i >= v[i].first)
        need[i] = 0;
      else
        need[i] = v[i].first - i;
    }
    int totneed = 0;
    priority_queue<int, vector<int>, greater<int> > cola;
    long long respuesta = 0;
    for (int i = n - 1; i >= 0; i--) {
      cola.push(v[i].second);
      if (totneed >= need[i]) continue;
      while (totneed < need[i]) {
        respuesta += cola.top();
        cola.pop();
        totneed++;
      }
    }
    cout << respuesta << endl;
  }
}
