#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char c = getchar();
  for (; !isdigit(c); c = getchar())
    if (c == '-') f = -1;
  for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
  return x * f;
}
struct node {
  int m, p;
  node() {}
  node(const int _m, const int _p) : m(_m), p(_p) {}
  bool operator<(const node x) const { return x.p > p; }
};
struct node1 {
  int m, p;
  node1() {}
  node1(const int _m, const int _p) : m(_m), p(_p) {}
  bool operator<(const node1 x) const {
    if (x.m != m) return x.m < m;
    return x.p < p;
  }
};
multiset<node> S;
priority_queue<node1> Q;
map<pair<int, int>, int> f;
int cost, tot;
inline void solve(int m) {
  multiset<node>::iterator op;
  for (op = S.begin(); op != S.end(); op++) {
    if ((*op).m <= m) {
      continue;
    } else
      break;
  }
  cost += (*op).p;
  tot++;
}
int main() {
  int T = read();
  while (T--) {
    int n = read(), a, b;
    S.clear();
    tot = cost = 0;
    f.clear();
    for (int i = 1; i <= n; ++i) {
      a = read(), b = read();
      f[make_pair(a, b)]++;
      S.insert(node(a, b));
      Q.push(node1(a, b));
    }
    while (!Q.empty()) {
      node1 u = Q.top();
      Q.pop();
      if (f[make_pair(u.m, u.p)] == 0) continue;
      if (tot >= u.m) {
        ++tot;
        continue;
      }
      while (tot < u.m) {
        solve(u.m);
        ++tot;
      }
    }
    printf("%d\n", cost);
  }
  return 0;
}
