#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll mod = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int TT = 1;
  cin >> TT;
  while (TT--) {
    ll n;
    cin >> n;
    vector<array<ll, 3>> A(n);
    for (ll i = 0; i < n; ++i) {
      cin >> A[i][0] >> A[i][1];
      A[i][2] = i;
    }
    ll ans = 0;
    sort(A.begin(), A.end());
    int have = n - 1;
    int buy = 0;
    multiset<ll> vals;
    for (int i = n - 1; i >= 0; --i) {
      vals.emplace(A[i][1]);
      if (have < A[i][0]) {
        ans += *vals.begin();
        vals.erase(vals.begin());
      } else {
        --have;
      }
    }
    cout << ans << '\n';
  }
}
