#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<long long> p(n), m(n);
    vector<vector<long long>> v(n + 1);
    for (long long i = 0; i < n; i++) {
      cin >> m[i] >> p[i];
      v[m[i]].push_back(i);
    }
    vector<long long> sum(n + 1);
    sum[0] = v[0].size();
    for (long long i = 1; i < n + 1; i++) {
      sum[i] = sum[i - 1] + v[i].size();
    }
    long long kol = 0;
    long long ans = 0;
    multiset<long long> st;
    for (long long i = n; i > 0; i--) {
      for (long long j = 0; j < v[i].size(); j++) {
        st.insert(p[v[i][j]]);
      }
      while (kol + sum[i - 1] < i) {
        ans += *st.begin();
        ++kol;
        st.erase(st.begin());
      }
    }
    cout << ans << "\n";
  }
}
