#include <bits/stdc++.h>
using namespace std;
struct node {
  long long v, p, id;
} t[2000001];
bool cmp2(node a, node b) { return a.p < b.p; }
struct cmp {
  bool operator()(node a, node b) { return a.v > b.v; }
};
priority_queue<node, vector<node>, cmp> q;
priority_queue<long long> q2;
long long vis[2000001];
signed main() {
  long long T;
  scanf("%I64d", &T);
  while (T--) {
    long long n;
    scanf("%I64d", &n);
    for (long long i = 1; i <= n; i++) vis[i] = 0;
    while (!q.empty()) q.pop();
    while (!q2.empty()) q2.pop();
    for (long long i = 1; i <= n; i++) {
      scanf("%I64d%I64d", &t[i].p, &t[i].v);
      t[i].id = i;
      q.push(t[i]);
    }
    sort(t + 1, t + n + 1, cmp2);
    long long cur = 0, ans = 0;
    for (long long i = 1; i <= n; i++) {
      while (cur != n && cur < t[i].p) {
        while (vis[q.top().id] == 1) q.pop();
        if (q2.size()) {
          ans += q.top().v - q2.top();
          q2.pop();
          vis[q.top().id] = 1;
          q.pop();
        } else {
          ans += q.top().v;
          vis[q.top().id] = 1;
          q.pop();
        }
        cur++;
      }
      if (cur == n) break;
      if (vis[t[i].id])
        q2.push(t[i].v);
      else
        ++cur;
      vis[t[i].id] = 1;
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
