#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1, -1, -1, 0, 1, -1, 0, 1};
int kx8[] = {1, 1, 2, 2, -1, -1, -2, -2};
int ky8[] = {2, -2, 1, -1, 2, -2, 1, -1};
long long bigmod(long long a, long long b, long long c) {
  if (b == 0) return 1 % c;
  long long x = bigmod(a, b / 2, c);
  x = (x * x) % c;
  if (b % 2 == 1) x = (x * a) % c;
  return x;
}
long long mod_inverse(long long a, long long mod) {
  return bigmod(a, mod - 2, mod);
}
long long a[100005 * 2], b[100005 * 2], vis[100005 * 2];
set<pair<int, int> > st;
vector<int> v[100005 * 2];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t, tt = 1;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 0; i < (n); i++) {
      cin >> b[i] >> a[i];
      v[b[i]].push_back(i);
      st.insert({a[i], i});
    }
    int cnt = 0;
    for (auto x : v[0]) {
      cnt++;
      st.erase(st.find({a[x], x}));
    }
    int lw = 0, hi = n, ans = 0, mid;
    while (lw <= hi) {
      mid = (lw + hi) / 2;
      int tot = cnt + mid;
      bool flg = 0;
      for (int i = 1; i < n; i++) {
        if (tot < i) {
          flg = 1;
          break;
        }
        tot += v[i].size();
      }
      if (!flg) {
        ans = mid;
        hi = mid - 1;
      } else {
        lw = mid + 1;
      }
    }
    long long cost = 0;
    int tot = cnt;
    long long sum = 0;
    priority_queue<int> pq;
    for (int i = 1; i < n; i++) {
      if (tot >= i) {
        for (auto x : v[i]) {
          if (vis[x]) continue;
          tot++;
          st.erase(st.find({a[x], x}));
        }
      } else {
        int need = i - tot;
        while (ans - pq.size() < need) {
          sum -= pq.top();
          pq.pop();
        }
        while (tot < i) {
          pair<int, int> p = *st.begin();
          pq.push(p.first);
          sum += p.first;
          tot++;
          st.erase(st.find(p));
          vis[p.second] = 1;
        }
        for (auto x : v[i]) {
          if (vis[x]) continue;
          tot++;
          st.erase(st.find({a[x], x}));
        }
      }
    }
    cout << sum << "\n";
    st.clear();
    for (int i = 0; i < (n + 2); i++) v[i].clear();
    for (int i = 0; i < (n + 2); i++) vis[i] = 0;
  }
  return 0;
}
