#include <bits/stdc++.h>
const int nn = 2e5 + 5;
int t, n;
struct vote {
  int m;
  long long p;
  int operator<(const vote &q) const { return m == q.m ? p > q.p : m < q.m; }
} a[nn];
int father[nn], need[nn];
std::priority_queue<long long, std::vector<long long>, std::greater<long long> >
    pq;
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d %lld", &a[i].m, &a[i].p);
    }
    std::sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; i++) {
      if (a[i].m < i) {
        father[i] = father[a[i].m];
        need[i] = need[father[i]];
      } else {
        father[i] = i;
        need[i] = need[i - 1] + 1;
      }
    }
    int now = n, cnt = 0;
    long long ans = 0;
    pq.push(a[n].p);
    while (need[now] > cnt) {
      if (father[now] == now) {
        ans += pq.top();
        pq.pop();
        --now;
        ++cnt;
        pq.push(a[now].p);
      } else {
        for (int i = father[now]; i < now; i++) pq.push(a[i].p);
        now = father[now];
      }
    }
    while (!pq.empty()) pq.pop();
    printf("%lld\n", ans);
  }
}
