#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e5 + 5;
const int mod = 1e9 + 7;
int n;
vector<int> v[maxn];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = (0); i < (n + 1); i++) v[i].clear();
    for (int i = (0); i < (n); i++) {
      int m, p;
      cin >> m >> p;
      v[m].push_back(p);
    }
    for (int i = (0); i < (n + 1); i++) sort(v[i].begin(), v[i].end());
    int x = 0, cnt = n, t = 0;
    priority_queue<int> q;
    long long ans = 0;
    for (int i = n; i >= 0; i--) {
      for (int j = (0); j < ((int)v[i].size()); j++) q.push(-v[i][j]);
      cnt -= (int)v[i].size();
      while (i > cnt + t) {
        ans -= q.top(), q.pop();
        t++;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
