#include <bits/stdc++.h>
using namespace std;
template <typename T>
using pqd = priority_queue<T>;
template <typename T>
using pqa = priority_queue<T, vector<T>, greater<T>>;
string to_string(string c) { return string(c); }
string to_string(char ch) { return string(1, ch); }
string to_string(bool b) { return b ? "true" : "false"; }
template <size_t N>
string to_string(bitset<N> B) {
  string second = "";
  for (long long i = 0; i < (long long)N; i++) second += (char)'0' + B[i];
  return second;
}
template <typename T, typename U>
string to_string(pair<T, U> P) {
  return "{" + to_string(P.first) + "," + to_string(P.second) + "}";
}
template <typename T>
string to_string(T A) {
  string second = "[";
  bool first = 0;
  for (auto x : A) {
    if (first) second += " ";
    first = 1;
    second += to_string(x);
  }
  return second + "]";
}
template <typename T, size_t N>
string to_string(T (&A)[N]) {
  string second = "[";
  bool first = 0;
  for (long long i = 0; i < N; i++) {
    if (first) second += " ";
    first = 1;
    second += to_string(A[i]);
  }
  return second + "]";
}
void _deb() { cerr << "\n"; }
template <typename T, typename... U>
void _deb(const T& t, const U&... u) {
  cerr << to_string(t);
  if (sizeof...(u)) cout << ", ";
  _deb(u...);
}
long long ceil(long long a, long long b) {
  return a / b + (a % b && (a ^ b) > 0);
}
long long floor(long long a, long long b) {
  return a / b - (a % b && (a ^ b) < 0);
}
long long SBITS(long long n) { return __builtin_popcountll(n); }
long long BITS(long long n) { return 63 - __builtin_clzll(n); }
const long long MX = 5e5 + 5;
const long long OO = 1e18;
const long long MOD = 1e9 + 7;
long long DX[8] = {1, 0, -1, 0, 1, -1, 1, -1};
long long DY[8] = {0, 1, 0, -1, 1, -1, -1, 1};
bool comp(pair<long long, long long> A, pair<long long, long long> B) {
  if (A.first != B.first)
    return A.first > B.first;
  else
    return A.second < B.second;
}
void solve() {
  long long n, ans = 0, ctr = 0;
  cin >> n;
  vector<pair<long long, long long>> vo(n);
  pqa<long long> pq;
  for (long long i = 0; i < n; i++) cin >> vo[i].first >> vo[i].second;
  sort(vo.begin(), vo.end(), comp);
  for (long long i = 0; i < n; i++) {
    pq.push(vo[i].second);
    if (n - (i + 1) + ctr < vo[i].first) {
      ans += pq.top();
      pq.pop();
      ctr++;
    }
  }
  cout << ans << "\n";
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) solve();
  return 0;
}
