#include <bits/stdc++.h>
using namespace std;
namespace IO {
const int buffer_size = 1e5 + 5;
char buf[buffer_size], *S, *T;
bool flag_EOF;
inline char read_char() {
  if (S == T) T = (S = buf) + fread(buf, 1, buffer_size, stdin);
  return S != T ? *(S++) : EOF;
}
inline int read_int() {
  int flag = 1;
  char c = read_char();
  while (c < '0' || c > '9') {
    if (c == EOF) {
      flag_EOF = true;
      return 0;
    }
    flag = (c == '-' ? -1 : 1);
    c = read_char();
  }
  int x = 0;
  while (c >= '0' && c <= '9') {
    x = x * 10 + (c ^ 48);
    c = read_char();
  }
  return x * flag;
}
char st[13];
int _top;
void Write(int x) {
  if (!x) {
    putchar('0');
    return;
  }
  if (x < 0) {
    putchar('-');
    x = -x;
  }
  while (x) {
    st[++_top] = x % 10 + '0';
    x /= 10;
  }
  while (_top > 0) putchar(st[_top--]);
}
}  // namespace IO
int n;
const int max_n = 2e5 + 5;
namespace DSU {
int f[max_n];
inline void init() {
  for (int i = 1; i <= n; ++i) f[i] = i;
}
int get_fa(int x) { return f[x] != x ? f[x] = get_fa(f[x]) : x; }
inline void merge(int x, int y) {
  x = get_fa(x), y = get_fa(y);
  if (x != y) {
    if (x < y) swap(x, y);
    f[x] = y;
  }
}
}  // namespace DSU
struct node {
  int m, p;
} q[max_n];
inline bool cmp(node x, node y) { return x.m < y.m; }
vector<int> l, r;
priority_queue<pair<int, int>, vector<pair<int, int> >,
               greater<pair<int, int> > >
    Q;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d%d", &q[i].m, &q[i].p);
    sort(q + 1, q + n + 1, cmp);
    DSU::init();
    for (int i = 2; i <= n; ++i) {
      if (q[i].m == q[i - 1].m || q[i].m <= i - 1) DSU::merge(i - 1, i);
    }
    l.clear();
    r.clear();
    for (int i = 1; i <= n; ++i) {
      if (l.size() && r.size() && DSU::get_fa(i) == l.back())
        r.back() = i;
      else {
        l.push_back(i);
        r.push_back(i);
      }
    }
    while (Q.size()) Q.pop();
    for (int i = 0; i < int(l.size()); ++i)
      for (int j = l[i]; j <= r[i]; ++j) Q.push(pair<int, int>(-i, q[j].p));
    int now = 0, cnt = 0;
    long long ans = 0;
    while (now < int(l.size())) {
      if (cnt >= q[l[now]].m) {
        cnt += r[now] - l[now] + 1;
        ++now;
      } else {
        ans += Q.top().second;
        Q.pop();
        ++cnt;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
