#include <bits/stdc++.h>
using namespace std;
struct node {
  long long m, p;
  friend bool operator<(node a, node b) { return a.p > b.p; }
} a[200010];
bool cmp(node a, node b) { return a.m > b.m; }
priority_queue<node> q;
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, ans = 0, x = 0;
    cin >> n;
    while (!q.empty()) q.pop();
    for (int i = 0; i < n; i++) {
      cin >> a[i].m >> a[i].p;
    }
    sort(a, a + n, cmp);
    for (int i = n; i > 0; i--) {
      while (a[x].m >= i) {
        q.push(a[x]);
        x++;
      }
      while (q.size() > n - i) {
        node t = q.top();
        q.pop();
        ans += t.p;
      }
    }
    cout << ans << endl;
  }
}
