#include <bits/stdc++.h>
using namespace std;
int a[200010];
int n, m;
long long s;
struct node {
  int l, r;
  bool operator<(const node z) const { return l < z.l; }
} c[200010];
int d[200010];
int main(int argc, char const *argv[]) {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d%d", &c[i].l, &c[i].r);
    sort(c + 1, c + n + 1);
    priority_queue<int, vector<int>, greater<int> > q;
    memset(d, 0, sizeof(int) * (n + 3 + 3));
    for (int i = 1; i <= n; i++)
      if (c[i].l > i - 1) d[i] = c[i].l - i + 1;
    int tot = 0;
    long long ans = 0;
    for (int i = n; i > 0; i--) {
      q.push(c[i].r);
      while (tot < d[i]) {
        ans += q.top();
        q.pop();
        tot++;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
