#include <bits/stdc++.h>
using namespace std;
int main() {
  cin.tie(0);
  cin.sync_with_stdio(0);
  int tc;
  cin >> tc;
  while (tc--) {
    int n;
    cin >> n;
    vector<pair<int, int>> p(n);
    for (int i = 0; i < n; ++i) cin >> p[i].first >> p[i].second;
    sort(p.begin(), p.end());
    vector<vector<pair<int, int>>> vals;
    vals.push_back({});
    int cmx = p[0].first;
    int mxdiff = cmx;
    for (int i = 0; i < n; ++i)
      if (p[i].first <= cmx) {
        vals.back().push_back(p[i]);
        ++cmx;
      } else {
        mxdiff = max(mxdiff, p[i].first - cmx);
        cmx = p[i].first + 1;
        vals.push_back({p[i]});
      }
    long long res = 0;
    while (mxdiff > vals.back().size()) {
      for (auto p : vals.back()) res += p.second;
      mxdiff -= vals.back().size();
      vals.pop_back();
    }
    map<int, int> cnt;
    auto care = vals.back();
    map<pair<int, int>, int> have;
    for (auto u : care) ++have[{u.first, -u.second}];
    int r = care[0].first + 1;
    for (int i = 1; i < care.size() + 1; ++i)
      if (i < care.size() && care[i].first == care[i - 1].first)
        ++r;
      else {
        cnt[care[i - 1].first] = r;
        if (i < care.size()) r = max(care[i].first + 1, r);
      }
    for (int i = 0; i < care.size(); ++i) swap(care[i].first, care[i].second);
    sort(care.begin(), care.end());
    for (int i = 0; i < care.size() && mxdiff; ++i) {
      int mx = cnt[care[i].second];
      auto it = cnt.lower_bound(mx);
      if (it == cnt.end() || mx > it->first) {
        res += care[i].first;
        if (care[i].first == --cnt[care[i].second]) cnt.erase(care[i].second);
        --mxdiff;
        --have[care[i]];
      }
    }
    for (auto it = have.rbegin(); it != have.rend() && mxdiff; ++it)
      while (it->second && mxdiff) {
        --it->second;
        --mxdiff;
        res += -it->first.second;
      }
    cout << res << endl;
  }
}
