#include <bits/stdc++.h>
using namespace ::std;
int ar[200005];
map<int, int> m;
int main() {
  int q;
  cin >> q;
  while (q--) {
    m.clear();
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        q;
    int n;
    cin >> n;
    for (int i = 0, l, r; i < n; i++)
      cin >> l >> r, q.push({r, l}), m[l]++, ar[i] = l;
    sort(ar, ar + n);
    int cnt = 0, i = 0;
    long long int ans = 0;
    while (i < n && ar[i] <= cnt) cnt++, i++;
    while (i < n) {
      int j = q.top().first, k = q.top().second;
      q.pop();
      if (k != cnt + 1 || m[k] > 1) {
        cnt++;
        ans += j;
        while (i < n && ar[i] <= cnt) cnt++, i++;
      }
    }
    cout << ans << '\n';
  }
}
