#include <bits/stdc++.h>
using namespace std;
bool cmp1(pair<int, int> p1, pair<int, int> p2) {
  if (p1.first == p2.first) return p1.second < p2.second;
  return p1.first < p2.first;
}
bool cmp2(pair<int, int> p1, pair<int, int> p2) {
  return p1.second < p2.second;
}
void solve() {
  int n;
  cin >> n;
  vector<pair<int, int> > v(n);
  int a, b;
  for (int i = 0; i < n; i++) {
    cin >> a >> b;
    v[i] = {a, b};
  }
  sort(v.begin(), v.end(), cmp1);
  vector<int> u(n);
  for (int i = 0; i < n; i++) {
    u[i] = v[i].first - i;
  }
  int x = 0, temp = INT_MIN;
  for (int i = 0; i < n; i++) {
    if (u[i] >= temp) {
      x = i;
      temp = u[i];
    }
  }
  auto itv = v.begin();
  for (int i = 0; i < x; i++) itv++;
  long long int ans = 0;
  if (temp > 0) {
    sort(itv, v.end(), cmp2);
    for (int i = x; i < n && temp--; i++) ans += 1ll * v[i].second;
  }
  cout << ans << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  cin >> t;
  for (int i = 1; i < t + 1; i++) {
    solve();
  }
  return 0;
}
