#include <bits/stdc++.h>
using namespace std;
const long long LL_INF = (long long)2e18 + 5;
struct voter {
  int M, P;
  bool operator<(const voter &other) const { return M < other.M; }
};
int N;
vector<voter> voters;
long long evaluate(int buy) {
  int index = 0;
  priority_queue<int> pq;
  for (int position = buy; position < N; position++) {
    while (index < N && voters[index].M <= position) pq.push(voters[index++].P);
    if (pq.empty()) return LL_INF;
    pq.pop();
  }
  long long sum = 0;
  while (index < N) sum += voters[index++].P;
  while (!pq.empty()) {
    sum += pq.top();
    pq.pop();
  }
  return sum;
}
void solve_case() {
  cin >> N;
  voters.resize(N);
  for (voter &v : voters) cin >> v.M >> v.P;
  sort(voters.begin(), voters.end());
  int min_buy = N, prefix_max = 0;
  for (int i = 1; i <= N; i++) {
    prefix_max = max(prefix_max, voters[i - 1].M - (i - 1));
    if (prefix_max <= N - i) min_buy = N - i;
  }
  cout << evaluate(min_buy) << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int T;
  cin >> T;
  while (T-- > 0) solve_case();
}
