#include <bits/stdc++.h>
using namespace std;
int main() {
  int tx;
  cin >> tx;
  while (tx--) {
    int n;
    cin >> n;
    int m[n];
    int p[n];
    for (int i = 0; i < n; i++) cin >> m[i] >> p[i];
    vector<int> ps[n];
    for (int i = 0; i < n; i++) ps[m[i]].push_back(p[i]);
    vector<vector<int>> grs(1);
    vector<int> tr(1);
    int ci = 0;
    int cur = 0;
    for (int i = 0; i < n; i++) {
      if (cur >= i) {
        cur += ps[i].size();
        for (auto el : ps[i]) {
          grs[ci].push_back(el);
        }
      } else if (!ps[i].empty()) {
        ci++;
        grs.push_back({});
        tr.push_back(i);
        for (auto el : ps[i]) grs[ci].push_back(el + 0);
        cur += ps[i].size();
      }
    }
    for (int i = 0; i < ci; i++) sort(grs[ci].rbegin(), grs[ci].rend());
    cur = 0;
    if (grs[0].size()) {
      cur += grs[0].size();
    }
    long long sum = 0;
    ci = 1;
    while (cur != n) {
      while (cur != n && cur != tr[ci]) {
        if (grs.back().empty()) {
          grs.pop_back();
        } else {
          int x = grs.back().back();
          if (x > 0)
            sum += x - 0;
          else
            sum += x;
          cur++;
          grs[grs.size() - 1].pop_back();
        }
      }
      if (cur == n) break;
      cur += grs[ci].size();
      ci++;
    }
    cout << sum << endl;
  }
}
