#include <bits/stdc++.h>
using namespace std;
int dp[5005][2];
void solve() {
  int n;
  cin >> n;
  vector<pair<int, int> > v;
  multiset<pair<int, int> > s;
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    v.push_back(make_pair(x, -y));
  }
  sort(v.begin(), v.end());
  int cnt = 0, extra = 0;
  long long ans = 0;
  for (int i = n - 1; i >= 0; i--) {
    while (v[i].first > i + cnt) {
      pair<int, int> p = *s.begin();
      ans += p.first;
      s.erase(s.begin());
      cnt++;
    }
    s.insert(make_pair(-v[i].second, v[i].first));
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
