#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int p[N];
int a[N];
vector<int> vec[N];
int sum[N];
void solve() {
  int n;
  scanf("%d", &n);
  int maxIdx = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &a[i], &p[i]);
    vec[a[i]].push_back(p[i]);
    maxIdx = max(maxIdx, a[i]);
  }
  for (int i = 0; i <= n; i++) {
    sort(vec[i].begin(), vec[i].end());
  }
  sum[0] = vec[0].size();
  for (int i = 1; i <= maxIdx; i++) {
    sum[i] = sum[i - 1] + vec[i].size();
  }
  multiset<pair<int, int> > S;
  long long ans = 0;
  int curNum = 0;
  for (int i = maxIdx; i >= 1; i--) {
    for (auto e : vec[i]) {
      S.insert(make_pair(e, i));
    }
    while (sum[i - 1] + curNum < i) {
      assert(!S.empty());
      ans += S.begin()->first;
      S.erase(S.begin());
      curNum++;
    }
  }
  printf("%lld\n", ans);
  for (int i = 0; i <= n; i++) {
    vec[i].clear();
  }
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    solve();
  }
  return 0;
}
