#include <bits/stdc++.h>
using namespace std;
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    long long m[n + 14], p[n + 14], mex = 0;
    vector<long long> vv[n + 14];
    for (long long i = 1; i <= n; i++) {
      cin >> m[i] >> p[i];
      vv[m[i]].push_back(p[i]);
      mex = max(mex, m[i]);
    }
    long long level = 0, non = 0, cost = 0, nibd = n;
    while (non < n) {
      non += vv[level].size();
      level++;
      if (non >= level) {
      } else {
        level = non;
        break;
      }
    }
    multiset<long long> s;
    long long bot = 0;
    for (long long i = mex; i >= 0; i--) {
      if (level >= i) {
        break;
      }
      nibd = nibd - vv[i].size();
      for (long long j = 0; j < vv[i].size(); j++) {
        s.insert(vv[i][j]);
      }
      if (nibd + bot < i) {
        for (long long j = 0; j < i - nibd - bot; j++) {
          auto it = s.begin();
          cost += (*it);
          s.erase(s.find((*it)));
        }
        bot += i - nibd - bot;
        non += i - nibd - bot;
      }
      while (non < n) {
        non += vv[level].size();
        level++;
        if (level >= i) {
          break;
        }
        if (non < level) {
          level = non;
          break;
        }
      }
    }
    cout << cost << '\n';
  }
}
