#include <bits/stdc++.h>
using namespace std;
multiset<int> s;
struct data {
  int p, num;
} p[500000];
bool operator<(data a, data b) { return a.num < b.num; }
long long ans;
void deal(int num) {
  while (!s.empty() && num) {
    ans += *s.begin();
    num--;
    s.erase(s.begin());
  }
}
int pos[500000], li[500000], len, cnt, t, n;
int main() {
  scanf("%d", &t);
  while (t--) {
    ans = 0;
    s.clear();
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d%d", &p[i].num, &p[i].p);
    }
    sort(p + 1, p + n + 1);
    for (int i = 1; i <= n; i++) {
      if (p[i].num != p[i - 1].num) {
        pos[++len] = i;
        li[len] = p[i].num - (i - 1);
      }
    }
    cnt = 0;
    for (int i = n; i >= 1; i--) {
      s.insert(p[i].p);
      if (i == pos[len]) {
        if (li[len] - cnt > 0) deal(li[len] - cnt), cnt = li[len];
        len--;
      }
    }
    printf("%I64d\n", ans);
  }
}
