#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long md = 1000000007) {
  long long res = 1;
  x %= md;
  while (y > 0) {
    if (y & 1) res = (res * x) % md;
    x = (x * x) % md;
    y = y >> 1;
  }
  return res % md;
}
long long max1(long long a, long long b, long long c = -1000000000000000000LL,
               long long d = -1000000000000000000LL) {
  long long mx1 = (a > b) ? a : b, mx2 = (c > d) ? c : d;
  return ((mx1 > mx2) ? mx1 : mx2);
}
struct node {
  vector<long long> v, w;
};
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long> > m(n);
    for (long long i = 0; i < n; i++) cin >> m[i].first >> m[i].second;
    sort(m.begin(), m.end());
    long long purchased = 0;
    long long cost = 0;
    multiset<long long> st;
    for (long long i = n - 1; i >= 0; i--) {
      long long cnt = 1;
      st.insert(m[i].second);
      while (i && m[i - 1].first == m[i].first) {
        st.insert(m[i - 1].second);
        cnt++;
        i--;
      }
      long long tot = i + purchased;
      if (tot >= m[i].first) continue;
      while (tot < m[i].first) {
        purchased++;
        tot++;
        auto it = st.begin();
        cost += *it;
        st.erase(it);
      }
    }
    cout << cost << '\n';
  }
}
