#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f, mod = 1000000007;
const double pi = 3.1415926535897932, eps = 1e-6;
int T, n, pre[200005], pos, add, mi;
pair<int, int> a[200005];
long long ans;
priority_queue<int, vector<int>, greater<int>> q;
vector<int> v[200005];
void solve() {
  ans = add = mi = 0;
  scanf("%d", &n);
  for (int(i) = (1); (i) <= (n); (i)++) {
    scanf("%d%d", &a[i].first, &a[i].second);
  }
  for (int(i) = (0); (i) <= (n); (i)++) pre[i] = 0;
  for (int(i) = (1); (i) <= (n); (i)++)
    pre[a[i].first]++, v[a[i].first].push_back(a[i].second);
  pre[0]--;
  mi = pre[0];
  for (int(i) = (1); (i) < (n); (i)++)
    pre[i] += pre[i - 1] - 1, mi = min(mi, pre[i]);
  for (int(i) = (0); (i) < (n); (i)++)
    if (pre[i] < 0) pos = i;
  for (int(i) = (pos + 1); (i) < (n); (i)++)
    for (int(j) = (0); (j) < (v[i].size()); (j)++) q.push(v[i][j]);
  while (add < -mi) {
    int t = q.top();
    q.pop();
    ans += t;
    add++;
    while (pos >= 0 && pre[pos] + add >= 0) {
      for (int(i) = (0); (i) < (v[pos].size()); (i)++) q.push(v[pos][i]);
      pos--;
    }
  }
  printf("%lld\n", ans);
  while (!q.empty()) q.pop();
  for (int(i) = (0); (i) < (n); (i)++) v[i].clear();
}
int main() {
  scanf("%d", &T);
  while (T--) solve();
  return 0;
}
