#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
constexpr ll mod = 998244353;
struct person {
  ll m, p, id;
  bool operator<(const person& o) const {
    if (m != o.m) return m < o.m;
    if (p != o.p) return p > o.p;
    return id < o.id;
  }
};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  ll t;
  cin >> t;
  for (ll i = 0; i < t; i++) {
    ll n;
    cin >> n;
    vector<person> in(n);
    for (ll j = 0; j < n; j++) {
      ll m, p;
      cin >> m >> p;
      in[j] = {m, p, j};
    }
    sort(begin(in), end(in));
    ll res = 0;
    ll bribed = 0;
    priority_queue<ll, vector<ll>, greater<ll>> pq;
    for (ll j = n - 1; j >= 0; j--) {
      pq.push(in[j].p);
      while (in[j].m - j > bribed) {
        res += pq.top();
        pq.pop();
        bribed++;
      }
    }
    cout << res << endl;
  }
}
