#include <bits/stdc++.h>
using namespace std;
long long int power(long long int x, long long int y, long long int p) {
  long long int r = 1;
  x = x % p;
  while (y) {
    if (y & 1) r = r * x % p;
    y = y >> 1;
    x = x * x % p;
  }
  return r;
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int csrand(int l = 0, int r = 1e9) {
  uniform_int_distribution<int> uid(l, r);
  return uid(rng);
}
const int N = 5e5 + 99;
vector<pair<int, int> > v[N];
long long int sz[N];
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t0;
  cin >> t0;
  while (t0--) {
    int n;
    cin >> n;
    for (int i = 0; i < n + 1; i++) v[i].clear();
    for (int i = 0; i < n; i++) {
      int x, y;
      cin >> x >> y;
      v[x].push_back({y, i});
    }
    for (int i = 0; i < n + 1; i++) sz[i] = v[i].size();
    for (int i = 1; i <= n; i++) sz[i] += sz[i - 1];
    long long int ans = 0, tk = 0;
    vector<pair<long long int, long long int> > reqq;
    for (int i = n; i >= 1; i--) {
      if (v[i].size() == 0) continue;
      int rem = i - sz[i - 1];
      if (tk >= rem) continue;
      rem -= tk;
      tk += rem;
      reqq.push_back({i, tk});
    }
    map<int, int> mp;
    for (int i = 0; i < reqq.size(); i++) {
      int st = reqq[i].first;
      int amt = reqq[i].second;
      vector<pair<int, int> > tmp;
      for (int j = st; j <= n; j++)
        for (auto x : v[j]) {
          if (mp[x.second]) continue;
          tmp.push_back(x);
        }
      sort(tmp.begin(), tmp.end());
      for (int i = 0; i < amt; i++) ans += tmp[i].first, mp[tmp[i].second] = 1;
    }
    cout << ans << '\n';
  }
}
