#include <bits/stdc++.h>
using namespace std;
int n, T;
const int maxn = 2e5 + 5;
int x, y;
vector<int> G[maxn];
multiset<int> S;
int sum[maxn];
int main() {
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 0; i <= n; i++) G[i].clear();
    for (int i = 1; i <= n; i++) {
      cin >> x >> y;
      G[x].push_back(y);
    }
    sum[0] = G[0].size();
    for (int i = 1; i <= n; i++) sum[i] = G[i].size() + sum[i - 1];
    S.clear();
    int cnt = 0;
    long long ans = 0;
    for (int i = n; i >= 0; i--) {
      int loss = i - (sum[i - 1] + cnt);
      for (auto v : G[i]) {
        S.insert(v);
      }
      while (loss > 0) {
        loss--;
        cnt++;
        auto x = *S.begin();
        ans += x;
        S.erase(x);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
