#include <bits/stdc++.h>
using namespace std;
const int N = (int)2e5 + 123, inf = 1e9, mod = 1e9 + 7;
const long long INF = 1e18;
int n, cnt;
pair<int, int> a[N];
vector<int> v[N];
bool was[N];
long long ans;
void add(int i) {
  int x = ++cnt;
  for (auto j : v[x])
    if (!was[j]) add(j);
}
void solve() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d%d", &a[i].second, &a[i].first);
  sort(a, a + n);
  for (int i = 0; i < n; i++) v[a[i].second].push_back(i);
  cnt = 0;
  for (auto j : v[0]) add(j);
  for (int i = 0; i < n; i++) {
    if (cnt >= a[i].second) continue;
    int mx = 0;
    ;
    bool ok = 0;
    for (auto j : v[cnt])
      if (was[j]) ok = 1, mx = max(mx, a[j].first);
    if (ok) ans -= mx;
    was[i] = 1;
    ans += a[i].first;
    add(i);
  }
  printf("%lld\n", ans);
  ans = 0;
  for (int i = 0; i < n; i++) {
    was[i] = 0;
    v[i].clear();
  }
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) solve();
  return 0;
}
