#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<pair<long long, int>, vector<pair<long long, int>>,
               greater<pair<long long, int>>>
    pq1;
priority_queue<pair<long long, int>> pq2;
int vis[200005];
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);
      vis[i] = 0;
    }
    sort(d + 1, d + n + 1, cmp);
    while (!pq1.empty()) pq1.pop();
    while (!pq2.empty()) pq2.pop();
    for (int i = 1; i <= n; i++) {
      pq1.push(make_pair(d[i].p, i));
    }
    int res = 0;
    long long ans = 0;
    for (int i = 1; i <= n; i++) {
      if (vis[i]) {
        pq2.push(make_pair(d[i].p, i));
        continue;
      }
      while (res < d[i].m) {
        res++;
        while (vis[pq1.top().second]) pq1.pop();
        ans += pq1.top().first;
        vis[pq1.top().second] = 1;
        pq1.pop();
        if (!pq2.empty()) {
          ans -= pq2.top().first;
          pq2.pop();
        }
      }
      if (!vis[i]) {
        vis[i] = 1;
        res++;
      } else {
        pq2.push(make_pair(d[i].p, i));
      }
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
