#include <bits/stdc++.h>
using namespace std;
struct node {
  long long p, m;
} q[200010];
int tmp(node s1, node s2) {
  if (s1.p == s2.p) return s1.m < s2.m;
  return s1.p < s2.p;
}
long long tr[1001000];
long long val[1001000];
void up(int rt) {
  if (val[rt * 2] < val[rt * 2 + 1]) {
    val[rt] = val[rt * 2];
    tr[rt] = tr[rt * 2 + 1];
  } else {
    val[rt] = val[rt * 2 + 1];
    tr[rt] = tr[rt * 2 + 1];
  }
}
void add(int l, int r, int rt, int pos, long long y) {
  if (l == pos && r == pos) {
    val[rt] = y;
    tr[rt] = rt;
    return;
  }
  int mid = (l + r) / 2;
  if (pos <= mid)
    add(l, mid, rt * 2, pos, y);
  else if (pos > mid)
    add(mid + 1, r, rt * 2 + 1, pos, y);
  up(rt);
}
int query(int l, int r, int rt, int L, int R) {
  if (l == L && r == R) {
    return rt;
  }
  int mid = (l + r) / 2;
  int ans = 0;
  if (R <= mid)
    ans = query(l, mid, rt * 2, L, R);
  else if (L > mid)
    ans = query(mid + 1, r, rt * 2 + 1, L, R);
  else {
    int q1 = query(l, mid, rt * 2, L, mid),
        q2 = query(mid + 1, r, rt * 2 + 1, mid + 1, R);
    if (val[q1] < val[q2])
      ans = q1;
    else
      ans = q2;
  }
  return ans;
}
int lv[200010];
void change(int rt) {
  while (rt / 2) {
    rt /= 2;
    up(rt);
  }
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long n;
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++) scanf("%lld%lld", &q[i].p, &q[i].m);
    long long sum = 0;
    sort(q + 1, q + 1 + n, tmp);
    for (int i = 1; i <= n; i++) {
      add(1, n, 1, i, 0x3f3f3f3f);
      lv[i] = max(0ll, q[i].p - i + 1);
    }
    long long ans = 0;
    for (int i = n; i >= 1; i--) {
      add(1, n, 1, i, q[i].m);
      lv[i] = max(lv[i] - sum, 0ll);
      for (int j = 1; j <= lv[i]; j++) {
        sum++;
        int now = query(1, n, 1, i, n);
        ans += val[now];
        now = tr[now];
        val[now] = 0x3f3f3f3f;
        change(now);
      }
    }
    printf("%lld\n", ans);
  }
}
