#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 (!q.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, rem;
    for (long long i = 1; i <= n; i++) {
      while (cur != n && cur < t[i].p) {
        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[i])
        q2.push(t[i].v), vis[i] = 0, rem = q.top().v - t[i].v;
      else
        ++cur;
    }
    printf("%I64d\n", ans + ((q2.top()) ? rem : 0));
  }
  return 0;
}
