#include <bits/stdc++.h>
using namespace std;
int n;
const int N = 2e5 + 3;
vector<int> g[N];
priority_queue<int, vector<int>, greater<int> > q;
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) g[i].clear();
    while (!q.empty()) q.pop();
    int ans = 0, nw = 0;
    int x, y;
    for (int i = 1; i <= n; i++) {
      scanf("%d%d", &x, &y);
      if (!x || !y)
        nw++;
      else if (x >= n)
        ans += x, nw++;
      else
        g[x].push_back(y);
    }
    for (int i = n - 1; i > 0; i--) {
      int sz = g[i].size();
      for (int j = 0; j < sz; j++) q.push(g[i][j]);
      int mn = n - (i - nw);
      while (q.size() > mn) {
        ans += q.top();
        q.pop();
      }
    }
    printf("%d\n", ans);
  }
  return 0;
}
