#include <bits/stdc++.h>
using namespace std;
const long long MX = 1e6 + 5;
const long long INF = 1e9;
const long long M = 1000000007;
int32_t main() {
  ios_base::sync_with_stdio(false);
  long long t = 1;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    long long ar[n];
    long long price[n];
    for (long long i = 0; i < n; i++) {
      cin >> ar[i] >> price[i];
    }
    sort(ar, ar + n);
    long long ct = ar[0];
    long long mn = ar[0];
    vector<pair<long long, long long> > tmp;
    long long init = 0;
    long long cnt = 0;
    for (long long i = 1; i < n; i++) {
      if (ct >= ar[i]) {
        ct++;
      } else {
        tmp.push_back(make_pair(mn, ct - mn + 1));
        mn = ar[i];
        ct = mn;
      }
    }
    tmp.push_back(make_pair(mn, ct - mn + 1));
    long long p = 0, ans = 0;
    for (auto itr : tmp) {
      p += itr.first - cnt;
      cnt += itr.second;
    }
    sort(price, price + n);
    for (long long i = 0; i < p; i++) {
      ans += price[i];
    }
    cout << ans << "\n";
    ;
  }
  return 0;
}
