#include <bits/stdc++.h>
using namespace std;
template <typename S, typename T>
ostream& operator<<(ostream& out, const pair<S, T> p) {
  out << "(" << p.first << "," << p.second << ")";
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
  for (auto a : v) out << a << " ";
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, const set<T>& S) {
  for (auto a : S) cout << a << " ";
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, const multiset<T>& S) {
  for (auto a : S) cout << a << " ";
  return out;
}
template <typename S, typename T>
ostream& operator<<(ostream& out, const map<S, T>& M) {
  for (auto m : M) cout << "(" << m.first << "->" << m.second << ") ";
  return out;
}
template <typename S, typename T>
pair<S, T> operator+(pair<S, T> a, pair<S, T> b) {
  return make_pair(a.first + b.first, a.second + b.second);
}
template <typename S, typename T>
pair<S, T> operator-(pair<S, T> a, pair<S, T> b) {
  return make_pair(a.first - b.first, a.second - b.second);
}
long long solve(vector<vector<int>>& A) {
  int n = A.size();
  multiset<int> S;
  int pref = n;
  int cnt = 0;
  long long ans = 0;
  for (int i = n - 1; i >= 0; i--) {
    pref -= A[i].size();
    for (auto a : A[i]) S.insert(a);
    while (pref + cnt < i) {
      ans += *S.begin();
      S.erase(S.begin());
      cnt++;
    }
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int cas, n;
  vector<vector<int>> A;
  cin >> cas;
  while (cas--) {
    cin >> n;
    A.resize(n);
    for (int i = 0; i < n; i++) A[i].clear();
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      A[m].push_back(p);
    }
    long long ans = solve(A);
    cout << ans << endl;
  }
  return 0;
}
