#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int maxm = 1e6 + 10;
const int inf = 0x3f3f3f3f;
const long long mod = 998244353;
const double eps = 1e-7;
int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int n;
struct Node {
  long long p;
  int m;
  bool operator<(const Node& x) const {
    if (m == x.m) return p > x.p;
    return m < x.m;
  }
} node[maxn];
int tmp[maxn];
bool check(int x) {
  int t = 0;
  for (int i = 1; i <= n; i++) {
    if (i + x - 1 < node[i].m) return false;
    t = i + x - 1 - node[i].m;
  }
  return t >= x;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> node[i].m >> node[i].p;
    sort(node + 1, node + 1 + n);
    int l = 0, r = n;
    int ans = 0;
    while (l <= r) {
      int mid = (l + r) >> 1;
      if (check(mid)) {
        ans = mid;
        r = mid - 1;
      } else
        l = mid + 1;
    }
    for (int i = 1; i <= n; i++) tmp[i] = i + ans - 1 - node[i].m;
    priority_queue<long long, vector<long long>, greater<long long>> q;
    vector<long long> t;
    long long res = 0;
    int x = tmp[n], lst = tmp[n];
    for (int i = n; i >= 1 && tmp[i] != 0; i--) {
      q.push(node[i].p);
      x = min(x, tmp[i]);
      if (x == lst - 1) {
        t.push_back(q.top());
        q.pop();
        lst = x;
      }
    }
    if (q.size()) {
      t.push_back(q.top());
      q.pop();
    }
    sort(t.begin(), t.end());
    for (int i = 0; i < ans; i++) res += t[i];
    cout << res << endl;
  }
  return ~~(0 - 0);
}
