#include <bits/stdc++.h>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
struct Node {
  int m, p;
};
Node e[200005];
bool cmp(Node x, Node y) { return x.m > y.m; }
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d%d", &e[i].m, &e[i].p);
    sort(e + 1, e + n + 1, cmp);
    e[n + 1].m = -1;
    int tot = 0;
    long long ans = 0;
    for (int i = 1; i <= n; i++) {
      q.push(e[i].p);
      if (e[i].m != e[i + 1].m) {
        for (; tot < e[i].m - (n - i) + (i == n) * (e[i].m != 0); tot++) {
          ans += q.top();
          q.pop();
          tot++;
        }
      }
    }
    while (!q.empty()) q.pop();
    printf("%lld\n", ans);
  }
}
