#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;
  }
  long long int ans = 0;
  int cnt = 0;
  priority_queue<int, vector<int>, greater<int> > pq;
  for (int i = n - 1; i >= 0; i--) {
    pq.push(v[i].second);
    while (u[i] > cnt) {
      ans += pq.top();
      pq.pop();
      cnt++;
    }
  }
  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;
}
