#include <bits/stdc++.h>
using namespace std;
void canhazfast() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
template <typename T>
T gcd(T a, T b) {
  return b ? gcd(b, a % b) : a;
}
template <typename T>
T extgcd(T a, T b, T &x, T &y) {
  T x0 = 1, y0 = 0, x1 = 0, y1 = 1;
  while (b) {
    T q = a / b;
    a %= b;
    swap(a, b);
    x0 -= q * x1;
    swap(x0, x1);
    y0 -= q * y1;
    swap(y0, y1);
  }
  x = x0;
  y = y0;
  return a;
}
int ctz(unsigned x) { return __builtin_ctz(x); }
int ctzll(unsigned long long x) { return __builtin_ctzll(x); }
int clz(unsigned x) { return __builtin_clz(x); }
int clzll(unsigned long long x) { return __builtin_clzll(x); }
int popcnt(unsigned x) { return __builtin_popcount(x); }
int popcntll(unsigned long long x) { return __builtin_popcountll(x); }
int bsr(unsigned x) { return 31 ^ clz(x); }
int bsrll(unsigned long long x) { return 63 ^ clzll(x); }
struct V {
  int m, p;
};
bool cmp(const V &a, const V &b) { return a.m != b.m ? a.m < b.m : a.p > b.p; }
bool used[200016];
V v[200016];
vector<int> wh[200016];
void solve() {
  int n, cnt = 0;
  long long ans = 0;
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      q;
  cin >> n;
  fill_n(used, n, false);
  for (int i = 0; i < n; ++i) cin >> v[i].m >> v[i].p;
  sort(v, v + n, cmp);
  for (int i = 0; i < n; ++i) {
    wh[v[i].m].push_back(i);
    q.emplace(v[i].p, i);
  }
  for (int i = 0; i < n; ++i) {
    if (used[i]) continue;
    while (cnt < v[i].m) {
      int j, pj;
      tie(pj, j) = q.top();
      q.pop();
      if (j == i || used[j]) continue;
      used[j] = true;
      ++cnt;
      ans += v[j].p;
    }
    if (cnt < v[i].m) ans += v[i].p;
    ++cnt;
    used[i] = true;
  }
  cout << ans << '\n';
}
int main() {
  canhazfast();
  int t;
  cin >> t;
  for (; t; --t) solve();
  return 0;
}
