#include <bits/stdc++.h>
using namespace std;
struct node {
  int m;
  long long p;
} d[200005];
int cmp(node a, node b) { return a.m < b.m; }
vector<int> v, v2;
priority_queue<long long, vector<long long>, greater<long long>> pq;
int nxt[100005];
int n;
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%I64d%d", &d[i].m, &d[i].p);
    }
    sort(d + 1, d + n + 1, cmp);
    nxt[n] = n + 1;
    for (int i = n - 1; i >= 1; i--) {
      if (d[i].m == d[i + 1].m)
        nxt[i] = nxt[i + 1];
      else
        nxt[i] = i + 1;
    }
    int ct = 0;
    int res = 0;
    v.clear();
    int pre = 0;
    while (!pq.empty()) pq.pop();
    v.push_back(1);
    for (int i = 1; i <= n; i = nxt[i]) {
      while (ct + i - 1 < d[i].m) {
        ct++;
      }
      if (i + ct > n) continue;
      if (d[i + ct].m <= i + ct - 1) continue;
      v.push_back(nxt[i]);
    }
    int pos = v.size();
    if (pos == 0) {
      printf("0\n");
      continue;
    }
    if (v[v.size() - 1] != n + 1) v.push_back(n + 1);
    ct = 0;
    res = 0;
    long long ans = 0;
    for (int i = 1; i <= n; i++) {
      if (i >= v[pos]) break;
      while (res < d[i].m) {
        if (pq.empty()) {
          pos--;
          for (int j = v[pos]; j < v[pos + 1]; j++) pq.push(d[j].p);
        }
        ct++;
        res++;
        ans += pq.top();
        pq.pop();
      }
      res++;
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
