#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 3;
int t, n, cnt;
long long ans;
priority_queue<int, vector<int>, greater<int> > Q;
struct node {
  int m, q;
  bool operator<(const node& B) const { return m > B.m || m == B.m && q < B.q; }
} A[N];
void solve() {
  cnt = 0;
  ans = 0;
  while (!Q.empty()) Q.pop();
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d%d", &A[i].m, &A[i].q);
  sort(A + 1, A + n + 1);
  for (int i = 1; i <= n; i++) {
    while (cnt + n - i < A[i].m) {
      cnt++;
      ans += Q.top();
      Q.pop();
    }
    Q.push(A[i].q);
  }
  printf("%lld\n", ans);
}
int main() {
  scanf("%d", &t);
  while (t--) solve();
  return 0;
}
