#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int q;
  cin >> q;
  for (int i = 0; i < q; ++i) {
    int n;
    cin >> n;
    vector<int> a[n];
    int cnt0 = 0;
    for (int j = 0; j < n; ++j) {
      int m, p;
      cin >> m;
      cin >> p;
      if (m == 0)
        cnt0++;
      else
        a[m - 1].push_back(p);
    }
    int pref[n];
    pref[0] = cnt0;
    for (int m = 1; m < n; ++m) {
      pref[m] = pref[m - 1] + a[m - 1].size();
    }
    int ans = 0;
    int cnt = 0;
    priority_queue<int> pq;
    for (int k = n - 1; k >= 0; --k) {
      if (a[k].size() == 0) continue;
      for (int j = 0; j < a[k].size(); ++j) {
        pq.push(-a[k][j]);
      }
      if (k + 1 <= pref[k] + cnt) continue;
      int need = k + 1 - pref[k] - cnt;
      while (need != 0) {
        need--;
        ans -= pq.top();
        pq.pop();
        cnt++;
      }
    }
    cout << ans << "\n";
  }
}
