#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
pair<int, int> arr[N];
int n;
void solve() {
  int bought = 0;
  long long ans = 0;
  cin >> n;
  for (int i = 0; i < int(n); i++) {
    cin >> arr[i].first >> arr[i].second;
    arr[i].second *= -1;
  }
  sort(arr, arr + n);
  multiset<int> ms;
  for (int i = int(n - 1); i >= 0; i--) {
    ms.insert(-arr[i].second);
    int need = arr[i].first - i - bought;
    while (need > 0) {
      ans += *ms.begin();
      ms.erase(ms.begin());
      bought++;
      need--;
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
