#include <bits/stdc++.h>
using namespace std;
signed main() {
  signed long long t;
  cin >> t;
  for (signed long long ii = 0; ii < t; ii++) {
    multiset<signed long long> s;
    signed long long n;
    cin >> n;
    vector<vector<signed long long>> mas(n);
    vector<signed long long> ct(n, 0);
    for (signed long long i = 0; i < n; i++) {
      signed long long a, b;
      cin >> a;
      cin >> b;
      if (a + 1 < n) ct[a + 1] = ct[a + 1] + 1;
      mas[a].push_back(b);
    }
    for (signed long long i = 1; i < n; i++) {
      ct[i] = ct[i] + ct[i - 1];
    }
    for (signed long long i = 0; i < n; i++) {
      ct[i] = ct[i] - i;
    }
    signed long long ans = 0;
    signed long long tec = 0;
    for (signed i = n - 1; i >= 0; i--) {
      for (signed long long x : mas[i]) {
        s.insert(x);
      }
      while (0 > ct[i] + tec) {
        ans += *s.begin();
        s.erase(s.begin());
        tec++;
      }
    }
    cout << ans << '\n';
    ;
  }
}
