#include <bits/stdc++.h>
using namespace std;
int q;
int n;
struct node {
  long long p;
  int m;
  int pos;
} a[5100];
int cmp(const node& c, const node& d) {
  if (c.m == d.m) return c.p < d.p;
  return c.m < d.m;
}
int vis[5100];
priority_queue<long long> op;
priority_queue<pair<int, long long> > op1;
map<pair<long long, pair<int, int> >, int> m1;
int main() {
  scanf("%d", &q);
  while (q--) {
    scanf("%d", &n);
    while (!op.empty()) op.pop();
    while (!op1.empty()) op1.pop();
    m1.clear();
    for (int i = 1; i <= n; i++) {
      scanf("%d%lld", &a[i].m, &a[i].p);
      vis[i] = 0;
    }
    sort(a + 1, a + 1 + n, cmp);
    for (int i = 1; i <= n; i++) {
      a[i].pos = i;
      pair<long long, pair<int, int> > r =
          make_pair(a[i].p, make_pair(a[i].pos, a[i].m));
      m1[r] = 1;
    }
    int temp = 0;
    long long ans = 0;
    int now = 1;
    while (now <= n) {
      while (now <= n && (a[now].m <= temp || vis[now] == 1)) {
        if (vis[now] == 0) vis[now] = 1, temp++;
        pair<long long, pair<int, int> > r =
            make_pair(a[now].p, make_pair(a[now].pos, a[now].m));
        m1.erase(r);
        now++;
      }
      if (now > n) break;
      while (!op1.empty()) {
        pair<int, long long> r1 = op1.top();
        if (-r1.first < a[now].m) {
          op1.pop();
          op.push(r1.second);
        } else
          break;
      }
      int temp1 = a[now].m - temp;
      int temp2 = a[now].pos;
      for (int i = 0; i < temp1; i++) {
        pair<long long, pair<int, int> > r = m1.begin()->first;
        if (!op.empty()) {
          ans -= op.top();
          op.pop();
        }
        temp++;
        ans += r.first;
        m1.erase(r);
        op1.push(make_pair(-r.second.second, r.first));
        vis[r.second.first] = 1;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
