#include <bits/stdc++.h>
using namespace std;
const double pi = 2 * acos(0.0);
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
const int dx8[] = {-1, 0, 1, 0, 1, 1, -1, -1};
const int dy8[] = {0, -1, 0, 1, 1, -1, 1, -1};
long long min(long long a, long long b) {
  if (a < b) return a;
  return b;
}
long long max(long long a, long long b) {
  if (a > b) return a;
  return b;
}
long long ceil1(long long a, long long b) { return (a + b - 1) / b; }
void read(vector<long long>& arr) {
  for (long long i = 0; i < int(arr.size()); i++) cin >> arr[i];
}
void read_graph(vector<vector<long long>>& g, long long m) {
  while (m--) {
    long long x, y;
    cin >> x >> y;
    x--, y--;
    g[x].push_back(y);
    g[y].push_back(x);
  }
}
void solve() {
  long long n;
  cin >> n;
  vector<vector<long long>> arr(n + 3);
  for (long long i = 0; i < n; i++) {
    long long x, y;
    cin >> x >> y;
    arr[x].push_back(y);
  }
  for (auto& x : arr) sort(x.begin(), x.end());
  vector<long long> pref(n + 3);
  for (long long i = 0; i <= n - 1; i++) {
    pref[i] = int(arr[i].size());
  }
  priority_queue<long long, vector<long long>, greater<long long>> pq;
  long long q = INT_MAX;
  long long cnt = 0;
  long long ans = 0;
  for (long long i = n - 1; i >= 0; i--) {
    if (int(arr[i].size()) == 0) continue;
    if (n - pref[i] >= i) {
      for (auto x : arr[i]) pq.push(x);
      q = i;
    } else {
      long long buy = min((n - pref[i] - i) * -1, int(arr[i].size()));
      cnt += buy;
      for (long long j = 0; j < buy; j++) ans += arr[i][j];
      for (long long j = buy; j < int(arr[i].size()); j++) {
        pq.push(arr[i][j]);
        q = i;
      }
    }
  }
  for (long long i = 0; i < q - cnt; i++) {
    ans += pq.top();
    pq.pop();
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) solve();
}
