#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long MAX = 5e3 + 7;
const long long INF = 1e15;
const long long dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
const long long dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
long long i, j, k, t, n, q, l, r, mid;
long long x, y, mini, cnt, cost, pos, ii;
priority_queue<long long, vector<long long>, greater<long long>> pq[MAX];
vector<pair<long long, long long>> v;
void solve() {
  cost = cnt = 0;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    cin >> x >> y;
    pq[x].push(y);
  }
  for (long long i = 0; i < n + 1; i++) {
    if (cnt < i) {
      mini = INF;
      if (pq[i].size() > 1)
        ii = i;
      else
        ii = i + 1;
      for (long long j = ii; j < n + 1; j++) {
        if (!pq[j].empty() && mini > pq[j].top()) {
          pos = j;
          mini = pq[j].top();
        }
      }
      if (mini != INF) {
        cost += mini;
        pq[pos].pop();
      } else {
        if (!pq[i].empty()) {
          cost += pq[i].top();
          pq[i].pop();
        }
      }
      cnt++;
      i--;
    } else {
      while (!pq[i].empty()) {
        cnt++;
        pq[i].pop();
      }
    }
  }
  cout << cost << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cin >> t;
  while (t--) solve();
  return 0;
}
