#include <bits/stdc++.h>
using namespace std;
int cmp(pair<int, int> a, pair<int, int> b) {
  return a.first == b.first ? a.second < b.second : a.first < b.first;
}
int main() {
  ios::sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) {
    int n;
    cin >> n;
    vector<pair<int, int>> all(n);
    priority_queue<int, vector<int>, greater<int>> min_prices;
    for (int i(0); i < n; i++) {
      cin >> all[i].first >> all[i].second;
    }
    sort(all.begin(), all.end(), cmp);
    int ct(0);
    long long ans(0);
    for (int i(n - 1); i >= 0; i--) {
      min_prices.push(all[i].second);
      while (all[i].first > i + ct) {
        ct++;
        ans += min_prices.top();
        min_prices.pop();
      }
    }
    cout << ans << endl;
  }
  return 0;
}
