#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> voters;
int n;
vector<pair<int, int>> table;
set<pair<int, int>> s;
long long r;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    int c = 0;
    for (int i = 0; i < n; i++) {
      int a, b;
      scanf("%d %d", &a, &b);
      if (a == 0) {
        c++;
      } else {
        voters.push_back(make_pair(a, b));
      }
    }
    n -= c;
    sort(voters.begin(), voters.end());
    for (int i = 0; i < n; i++) {
      if (voters[i].first > c) {
        table.push_back(make_pair(voters[i].first - c, i));
        c = voters[i].first;
      } else {
        c++;
      }
    }
    int ma = 0, la = n;
    for (int i = (int)table.size() - 1; i >= 0; i--) {
      for (int j = la - 1; j >= table[i].second; j--) {
        s.insert(make_pair(voters[j].second, j));
      }
      la = table[i].second;
      if (table[i].first > ma) {
        int p = table[i].first - ma;
        while (p--) {
          r += s.begin()->first;
          s.erase(s.begin());
        }
        ma = table[i].first;
      }
    }
    printf("%lld\n", r);
    voters.clear();
    s.clear();
    table.clear();
    r = 0;
  }
}
