#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cout.tie(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<long long, long long> > vec(n);
    for (int i = 0; i < n; ++i) {
      cin >> vec[i].first >> vec[i].second;
    }
    sort(vec.begin(), vec.end());
    map<long long, long long> mp;
    map<long long, long long> mi;
    for (int i = 0; i < vec.size(); ++i) {
      mp[vec[i].first]++;
      if (mi.count(vec[i].first) == 0) {
        mi[vec[i].first] = i;
      }
    }
    long long cnt = 0;
    vector<pair<long long, long long> > fa;
    for (auto e : mp) {
      if (e.first > cnt) {
        while ((!fa.empty()) && (fa.back().second <= e.first - cnt)) {
          fa.pop_back();
        }
        fa.push_back(make_pair((mi[e.first]), (e.first - cnt)));
      }
      cnt += e.second;
    }
    multiset<long long> st;
    long long cur = n;
    reverse(fa.begin(), fa.end());
    long long ans = 0;
    long long cur_cc = 0;
    for (auto e : fa) {
      while (cur > e.first) {
        st.insert(vec[cur - 1].second);
        cur--;
      }
      while (cur_cc < e.second) {
        ans += *st.begin();
        st.erase(st.begin());
        cur_cc++;
      }
    }
    cout << ans << '\n';
  }
  cout << endl;
  return 0;
}
