#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
const int MOD = 1e9 + 7;
const long double PI = 3.1415926535898;
const long long INF = LLONG_MAX;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<int, int>> v(n);
    for (int i = 0; i < n; i++) {
      cin >> v[i].first >> v[i].second;
    }
    sort(v.begin(), v.end());
    long long ans = 0;
    multiset<int> s;
    int num = 0;
    for (int i = n - 1; i >= 0; i--) {
      s.insert(v[i].second);
      int req = (v[i].first - i - num);
      while (req > 0) {
        ans += *s.begin();
        s.erase(s.begin());
        num++;
        req--;
      }
    }
    cout << ans << "\n";
  }
}
