#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 100, INF = 1e18;
pair<long long, long long> mp[N];
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    for (long long i = 0; i < n; i++) cin >> mp[i].first >> mp[i].second;
    sort(mp, mp + n);
    for (long long i = 0; i < n; i++) mp[i].first -= i;
    multiset<long long> s;
    long long cnt = 0, sum = 0;
    for (long long i = n - 1; i >= 0; i--) {
      s.insert(mp[i].second);
      if (cnt < mp[i].first) cnt++, sum += *s.begin(), s.erase(s.begin());
    }
    cout << sum << "\n";
  }
}
