#include <bits/stdc++.h>
using namespace std;
const int INF = 2e9;
const long long BIG_INF = 1e18;
const long long MOD = 1e9 + 7;
const int maxn = 2 * 1e5 + 5;
int Size[maxn], pref_sum[maxn];
vector<long long> a[maxn];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) a[i].clear();
    for (int i = 0; i < n; i++) {
      int m;
      long long p;
      cin >> m >> p;
      a[m].push_back(p);
    }
    for (int i = 0; i < n; i++) Size[i] = (int)a[i].size();
    for (int i = 1; i < n; i++) pref_sum[i] = pref_sum[i - 1] + Size[i - 1];
    int cnt = 0;
    long long ans = 0;
    multiset<long long> ms;
    for (int i = n - 1; i >= 0; i--) {
      for (int j = 0; j < Size[i]; j++) ms.insert(a[i][j]);
      if (pref_sum[i] + cnt < i) {
        int j = i - pref_sum[i] - cnt;
        while (!ms.empty() && j--) {
          cnt++;
          ans += *ms.begin();
          ms.erase(ms.begin());
        }
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
