#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
vector<int> ps[200000];
int sum[200000];
int main() {
  int T;
  cin >> T;
  for (int t = 0; t < T; t++) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) ps[i].clear();
    for (int i = 0; i < n; i++) {
      int p, m;
      cin >> m >> p;
      ps[m].push_back(p);
    }
    sum[0] = 0;
    for (int i = 0; i + 1 < n; i++) {
      sum[i + 1] = sum[i] + ps[i].size();
    }
    priority_queue<int, vector<int>, greater<int>> Q;
    int cnt = 0;
    long long ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      for (int p : ps[i]) Q.push(p);
      int k = max(i - sum[i] - cnt, 0);
      for (int j = 0; j < k; j++) {
        ans += Q.top();
        Q.pop();
      }
      cnt += k;
    }
    cout << ans << endl;
  }
}
