#include <bits/stdc++.h>
using namespace std;
const int maxn = 211111;
int n, fa[maxn];
struct node {
  int m, p, id;
} e[maxn], t[maxn];
bool cmp1(node a, node b) { return a.m < b.m; }
bool cmp2(node a, node b) {
  if (a.p == b.p) return a.id < b.id;
  return a.p < b.p;
}
bool vis[maxn];
int main() {
  int T;
  cin >> T;
  while (T--) {
    memset(vis, 0, sizeof vis);
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> e[i].m >> e[i].p;
    }
    sort(e + 1, e + 1 + n, cmp1);
    for (int i = 1; i <= n; i++) {
      t[i].m = e[i].m;
      t[i].p = e[i].p;
      e[i].id = t[i].id = i;
    }
    sort(t + 1, t + 1 + n, cmp2);
    int now = 0, u = 1;
    for (int i = 1; i <= n; i++) {
      if (e[i].m > now) {
        now = e[i].m;
        u = i;
        fa[i] = u;
      } else {
        fa[i] = u;
        now++;
      }
    }
    now = 0;
    int ans = 0, pb = 1;
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      while (now < e[i].m) {
        if (t[pb].id > i) ans += t[pb].p;
        vis[t[pb].id] = true;
        if (t[pb].id > i) now++;
        pb++;
      }
      now++;
    }
    cout << ans << endl;
  }
  return 0;
}
