#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const long long linf = 4000000000000000000LL;
const long long inf = 998244353;
const long double pi = 3.1415926535;
void pv(vector<int> a) {
  for (auto& x : a) cout << x << " ";
  cout << '\n';
}
void pv(vector<long long> a) {
  for (auto& x : a) cout << x << " ";
  cout << '\n';
}
void pv(vector<vector<int> > a) {
  for (int i = (0); i < (int(a.size())); ++i) {
    cout << i << '\n';
    pv(a[i]);
    cout << '\n';
  }
}
void pv(vector<vector<long long> > a) {
  for (int i = (0); i < (int(a.size())); ++i) {
    cout << i << '\n';
    pv(a[i]);
  }
  cout << '\n';
}
void pv(vector<string> a) {
  for (auto& x : a) cout << x << '\n';
  cout << '\n';
}
void setIO(string second) {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  if (int(second.size())) {
    freopen((second + ".out").c_str(), "r", stdin);
    if (second != "test1") freopen((second + ".in").c_str(), "w", stdout);
  }
}
long long solve() {
  int n;
  cin >> n;
  vector<vector<int> > a(n);
  for (int i = (0); i < (n); ++i) {
    int x, y;
    cin >> x >> y;
    a[x].push_back(y);
  }
  for (int i = (0); i < (n); ++i) sort(a[i].begin(), a[i].end());
  vector<int> prefix(n + 1);
  for (int i = (0); i < (n); ++i) prefix[i + 1] = prefix[i] + int(a[i].size());
  long long ans = 0;
  multiset<int> cur;
  int count = 0;
  for (int i = (n)-1; i >= (0); --i) {
    int add = i - prefix[i] - count;
    add = max(add, 0);
    for (auto& x : a[i]) cur.insert(x);
    assert(add <= int(cur.size()));
    count += add;
    while (add) {
      add--;
      ans += *cur.begin();
      cur.erase(cur.begin());
    }
  }
  return ans;
}
int main() {
  setIO("");
  int testc;
  cin >> testc;
  while (testc--) {
    cout << solve() << '\n';
  }
}
