#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long q;
  cin >> q;
  for (long long _ = (0); _ < ((q)); ++_) {
    long long n;
    cin >> n;
    vector<long long> a[n];
    for (long long i = (0); i < ((n)); ++i) {
      long long x, y;
      cin >> x >> y;
      a[x].push_back(y);
    }
    vector<long long> s(n, 0);
    for (long long i = (0); i < ((n)); ++i) s[i] = a[i].size();
    for (long long i = (0); i < ((n - 1)); ++i) s[i + 1] += s[i];
    priority_queue<long long, vector<long long>, greater<long long>> que;
    long long ans = 0, now = 0;
    for (long long i = ((n)-1); i >= (0); --i) {
      if (s[i] + now >= i + 1) {
        for (long long x : a[i]) que.push(x);
        continue;
      }
      for (long long _ = (0); _ < (((i + 1) - (s[i] + now))); ++_)
        ans += que.top(), que.pop();
      now += (i + 1) - (s[i] + now);
      for (long long x : a[i]) que.push(x);
    }
    cout << ans << "\n";
  }
  return 0;
}
