#include <bits/stdc++.h>
using namespace std;
struct pos {
  vector<int> v;
  long long pref;
};
long long t, n, i, sum, ans, cnt, nr, p;
multiset<int> s;
map<int, pos> m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> t;
  while (t) {
    t--;
    cin >> n;
    m.clear();
    for (i = 1; i <= n; i++) {
      cin >> nr >> p;
      m[nr].v.push_back(p);
    }
    sum = 0;
    for (auto &it : m) {
      it.second.pref = sum;
      sum += it.second.v.size();
    }
    auto it = prev(m.end());
    cnt = 0;
    ans = 0;
    s.clear();
    while (true) {
      for (int it2 : it->second.v) s.insert(it2);
      if (it->second.pref + cnt < it->first) {
        nr = it->first - it->second.pref - cnt;
        cnt += nr;
        while (nr) {
          nr--;
          ans += *s.begin();
          s.erase(s.begin());
        }
      }
      if (it == m.begin()) break;
      --it;
    }
    cout << ans << '\n';
  }
  return 0;
}
