#include <bits/stdc++.h>
using namespace std;
struct Heap {
  vector<pair<int, int>> p;
  unordered_map<int, int> M;
  int count = 0;
};
void insert(Heap* H, pair<int, int> n) {
  int i = H->count;
  H->count++;
  H->p.push_back(n);
  while (i > 0 && H->p[(i - 1) / 2] > n) {
    H->M[H->p[(i - 1) / 2].second] = i;
    H->p[i] = H->p[(i - 1) / 2];
    i = (i - 1) / 2;
  }
  H->M[n.second] = i;
  H->p[i] = n;
}
void ProtocolDown(Heap* H, int i) {
  int l = 2 * i + 1;
  int r = 2 * i + 1;
  int m;
  if (l < H->count && H->p[l] < H->p[i])
    m = l;
  else
    m = i;
  if (r < H->count && H->p[r] < H->p[m]) m = r;
  if (m != i) {
    H->M[H->p[i].second] = m;
    H->M[H->p[m].second] = i;
    pair<int, int> t = H->p[i];
    H->p[i] = H->p[m];
    H->p[m] = t;
    ProtocolDown(H, m);
  }
}
int Min(Heap* H) {
  pair<int, int> m = H->p[0];
  H->p[0] = H->p[H->count - 1];
  H->count--;
  H->p.pop_back();
  H->M.erase(m.second);
  ProtocolDown(H, 0);
  return m.first;
}
void showIndex(Heap* H, pair<int, int> p) {
  if (H->M.find(p.second) != H->M.end())
    cout << H->M[p.second];
  else
    cout << -1;
}
void Delete(Heap* H, int i) {
  if (H->M.find(i) != H->M.end()) {
    int index = H->M[i];
    H->p[index] = H->p[H->count - 1];
    H->count--;
    H->M.erase(i);
    H->p.pop_back();
    ProtocolDown(H, index);
  }
}
int main() {
  int t;
  cin >> t;
  int out[t];
  for (int i = 0; i < t; i++) {
    int n;
    cin >> n;
    vector<pair<int, int>> table(n);
    Heap cost;
    Heap person;
    int price = 0;
    int convinced = 0;
    for (int j = 0; j < n; j++) {
      cin >> table[j].first >> table[j].second;
      if (table[j].first == 0)
        convinced++;
      else {
        pair<int, int> a = {table[j].first, j};
        pair<int, int> b = {table[j].second, j};
        insert(&cost, b);
        insert(&person, a);
      }
    }
    if (convinced > 0) {
      while (convinced < n && convinced >= person.p[0].first) {
        convinced++;
        Delete(&cost, person.p[0].second);
        Delete(&person, person.p[0].second);
      }
    }
    while (convinced < n) {
      price += cost.p[0].first;
      Delete(&person, cost.p[0].second);
      Delete(&cost, cost.p[0].second);
      convinced++;
      while (convinced < n && convinced >= person.p[0].first) {
        convinced++;
        Delete(&cost, person.p[0].second);
        Delete(&person, person.p[0].second);
      }
    }
    out[i] = price;
  }
  for (int i = 0; i < t; i++) {
    cout << out[i] << endl;
  }
  return 0;
}
