#include <bits/stdc++.h>
using namespace std;
template <class T>
bool ckmax(T &x, T y) {
  return x < y ? x = y, 1 : 0;
}
template <class T>
bool ckmin(T &x, T y) {
  return x > y ? x = y, 1 : 0;
}
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = 0;
    ch = getchar();
  }
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return f ? x : -x;
}
const int N = 200005;
int n;
struct node {
  int a, b;
} a[N];
inline bool cmp(const node &a, const node &b) {
  return a.a != b.a ? a.a > b.a : a.b > b.b;
}
void Main() {
  priority_queue<int, vector<int>, greater<int> > pq;
  long long ans = 0, now = 0, mxv = 0;
  n = read();
  for (int i = 1, iend = n; i <= iend; ++i)
    a[i].a = read(), a[i].b = read(), ans += a[i].b;
  sort(a + 1, a + n + 1, cmp);
  for (int i = 1, iend = n; i <= iend; ++i) {
    now += a[i].b, pq.push(a[i].b);
    if ((int)(pq).size() > n - a[i].a) now -= pq.top(), pq.pop();
    ckmax(mxv, now);
  }
  printf("%lld\n", ans -= mxv);
}
signed main() {
  for (int T = read(); T; --T) Main();
}
