#include <bits/stdc++.h>
using namespace std;
int t;
inline void read() { cin >> t; }
inline void solve() {
  for (int g = 0; g < (t); g++) {
    set<pair<pair<int, int>, int> > s1;
    set<pair<pair<int, int>, int> > s2;
    int n;
    cin >> n;
    int k1, k2;
    for (int i = 0; i < (n); i++) {
      cin >> k1 >> k2;
      s2.insert({{k1, k2}, i});
      s1.insert({{k2, k1}, i});
    }
    long long otv = 0;
    int c = 0;
    int cur = 0;
    while (s1.size()) {
      long long t_sum = 0;
      long long t_cnt = 0;
      long long t_del = 0;
      vector<pair<pair<int, int>, int> > v;
      while (s2.size() && s2.begin()->first.first == cur) {
        pair<pair<int, int>, int> e = *s2.begin();
        if (cur - c > t_cnt) {
          t_sum += e.first.second;
          t_del++;
        }
        t_cnt++;
        v.push_back({{e.first.second, e.first.first}, e.second});
        s2.erase(e);
      }
      if (t_del == t_cnt) {
        for (pair<pair<int, int>, int> x : v) {
          s1.erase(x);
        }
      }
      long long t2_sum = 0;
      long long t2_cnt = 0;
      for (pair<pair<int, int>, int> x : s1) {
        if (t2_cnt == cur - c) break;
        t2_sum += x.first.first;
        t2_cnt++;
      }
      if (t2_cnt == cur - c) {
        c += t2_cnt + t_cnt;
        otv += t2_sum;
        for (int i = 0; i < (t2_cnt); i++) {
          pair<pair<int, int>, int> e = *s1.begin();
          s2.erase({{e.first.second, e.first.first}, e.second});
          s1.erase(e);
        }
      }
      for (pair<pair<int, int>, int> x : v) {
        s1.erase(x);
      }
      if (s2.size()) cur = s2.begin()->first.first;
    }
    cout << otv << '\n';
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  read();
  solve();
}
