#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e5 + 5, inf = 1e18;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    vector<pair<pair<long long int, long long int>, long long int> > v1, v2;
    long long int c[n], m[n];
    for (long long int i = 0; i < n; ++i) {
      cin >> m[i] >> c[i];
      v2.push_back(make_pair(make_pair(m[i], c[i]), i));
    }
    sort(v2.begin(), v2.end());
    set<pair<long long int, long long int> > S;
    long long int cnt = 0;
    long long int mk[n];
    long long int ans = 0;
    memset(mk, 0, sizeof(mk));
    for (long long int i = n - 1; i >= 0; i--) {
      if (mk[i] == 0) {
        S.insert(make_pair(v2[i].first.second, v2[i].second));
        mk[i] = 1;
      }
      long long int z = v2[i].first.first;
      if (i + cnt < z) {
        auto it = S.begin();
        ans += (*it).first;
        S.erase(it);
        cnt++;
        i++;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
