#include <bits/stdc++.h>
using namespace std;
template <class TH>
void _dbg(const char *sdbg, TH h) {
  cerr << sdbg << '=' << h << endl;
}
template <class TH, class... TA>
void _dbg(const char *sdbg, TH h, TA... a) {
  while (*sdbg != ',') cerr << *sdbg++;
  cerr << '=' << h << ',';
  _dbg(sdbg + 1, a...);
}
template <class L, class R>
ostream &operator<<(ostream &os, pair<L, R> p) {
  return os << "(" << p.first << ", " << p.second << ")";
}
template <class Iterable,
          class = typename enable_if<!is_same<string, Iterable>::value>::type>
auto operator<<(ostream &os, Iterable v) -> decltype(os << *begin(v)) {
  os << "[";
  for (auto vv : v) os << vv << ", ";
  return os << "]";
}
const int inf = 0x3f3f3f3f;
const long long infll = 0x3f3f3f3f3f3f3f3fll;
template <class T>
int sign(T x) {
  return (x > 0) - (x < 0);
}
template <class T>
T abs(const T &x) {
  return (x < T(0)) ? -x : x;
}
int main() {
  cin.sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    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());
    multiset<int> vals;
    int b = 0;
    long long ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      int k = i;
      vals.insert(p[i].second);
      while (i > 0 && p[i - 1].first == p[k].first) {
        i--;
        vals.insert(p[i].second);
      }
      while (b + i < p[i].first) {
        ans += *vals.begin();
        vals.erase(vals.begin());
        b++;
      }
    }
    cout << ans << endl;
  }
}
