#include <bits/stdc++.h>
using namespace std;
pair<long long, long long> add_pair(pair<long long, long long> a,
                                    pair<long long, long long> b) {
  return make_pair(a.first + b.first, a.second + b.second);
}
long long power(long long a, long long b) {
  long long res = 1;
  a = a % ((long long)1e9 + 7);
  while (b > 0) {
    if (b & 1) {
      res = (res * a) % ((long long)1e9 + 7);
      b--;
    }
    a = (a * a) % ((long long)1e9 + 7);
    b >>= 1;
  }
  return res;
}
long long fermat_inv(long long y) { return power(y, ((long long)1e9 + 7) - 2); }
long long gcd(long long a, long long b) { return (b == 0) ? a : gcd(b, a % b); }
long long mul(long long a, long long b) {
  return (a * (b % ((long long)1e9 + 7))) % ((long long)1e9 + 7);
}
long long sub(long long a, long long b) {
  return ((a - b) % ((long long)1e9 + 7) + ((long long)1e9 + 7)) %
         ((long long)1e9 + 7);
}
long long add(long long a, long long b) {
  return ((a + b) % ((long long)1e9 + 7) + ((long long)1e9 + 7)) %
         ((long long)1e9 + 7);
}
void solve() {
  long long n, i, j, cnt, sum, cnt2;
  cin >> n;
  vector<pair<long long, long long> > a(n);
  for (i = (0); i < (n); i += (1)) cin >> a[i].first >> a[i].second;
  sort(a.begin(), a.end());
  sum = 0;
  cnt = 0;
  multiset<long long> s;
  for (i = (n - 1); i > (-1); i -= (1)) {
    if (a[i].first - cnt > i) {
      s.insert(a[i].second);
      for (j = (i - 1); j > (-1); j -= (1)) {
        if (a[j].first != a[i].first) break;
        s.insert(a[j].second);
      }
      j++;
      cnt2 = i - j + 1;
      cnt += cnt2;
      while (cnt2--) {
        sum += *s.begin();
        s.erase(s.begin());
      }
      i = j;
    } else {
      s.insert(a[i].second);
    }
  }
  cout << sum << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
