#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 9;
bool cmp(const int &A, const int &B) { return A > B; }
vector<int> G[maxn];
int n;
int L[maxn];
priority_queue<int, vector<int>, greater<int>> Q;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int T(1), cas(0);
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = (0); i <= int(n); ++i) G[i].clear();
    for (int i = (1); i <= int(n); ++i) {
      int p, m;
      cin >> m >> p;
      G[m].push_back(p);
    }
    for (int i = (1); i <= int(n); ++i) sort(G[i].begin(), G[i].end(), cmp);
    L[0] = 0;
    for (int i = (1); i <= int(n); ++i) {
      L[i] = L[i - 1] + G[i - 1].size() - 1;
    }
    int add(0);
    long long ans(0);
    for (int i = n; i; --i) {
      for (auto &v : G[i]) Q.push(v);
      while (add + L[i] < 0) {
        ++add;
        ans += Q.top();
        Q.pop();
      }
    }
    while (Q.size()) Q.pop();
    cout << ans << '\n';
  }
  return 0;
}
