#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const int MOD = 1e9 + 7;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
const int N = 2e5 + 1;
int T, n;
vector<int> F[N];
long long res = 0, s[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 0; i < n; i++) F[i].clear();
    for (int i = 1; i <= n; i++) {
      int m, p;
      cin >> m >> p;
      F[m].push_back(p);
    }
    for (int i = 0; i < n; i++) {
      s[i] = (i == 0) ? F[i].size() : s[i - 1] + 1ll * F[i].size();
    }
    res = 0;
    priority_queue<int, vector<int>, greater<int> > Pr;
    int used = 0;
    for (int i = n - 1; i > -1; i--) {
      if (F[i].size() == 0) continue;
      for (int x : F[i]) Pr.push(x);
      int need = i - (((i == 0) ? 0 : s[i - 1]) + used);
      while (need > 0) {
        res += 1ll * Pr.top();
        Pr.pop();
        need--;
        used++;
      }
    }
    cout << res << '\n';
  }
  return 0;
}
