#include <bits/stdc++.h>
using namespace std;
long long mod1 = 1000000007ll;
long long mod2 = 998244353ll;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long power(long long x, long long y) {
  if (y == 0) return 1;
  long long p = power(x, y / 2);
  p = (p * p) % mod1;
  if (y % 2) return (p * x) % mod1;
  return p;
}
void solve() {
  long long n;
  cin >> n;
  priority_queue<pair<long long, long long> > pq;
  priority_queue<long long> q;
  for (int i = 0; i < n; i++) {
    long long x, y;
    cin >> x >> y;
    pair<long long, long long> p;
    p.first = x;
    p.second = -y;
    pq.push(p);
  }
  long long ans = 0;
  long long t = 0;
  while (!pq.empty()) {
    pair<long long, long long> p = pq.top();
    long long x = p.first, r = 0;
    while (p.first == x) {
      q.push(p.second);
      r++;
      pq.pop();
      if (pq.empty()) break;
      p = pq.top();
    }
    long long n1 = r;
    if (x - t > n - n1) {
      n1 = x - t - n + n1;
      t += n1;
      while (n1--) {
        long long c = q.top();
        ans -= c;
        q.pop();
      }
    }
    n -= r;
  }
  cout << ans << endl;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  cin >> t;
  while (t--) solve();
  return 0;
}
