#include <bits/stdc++.h>
using namespace std;
const int MX = 2e5 + 5;
int t, n, m, p;
vector<pair<int, int> > v;
int main() {
  cin.tie(nullptr), ios::sync_with_stdio(false);
  cin >> t;
  while (t--) {
    cin >> n;
    v.clear();
    for (int i = 0; i < n; i++) {
      cin >> m >> p;
      v.push_back(make_pair(m, p));
    }
    sort(v.begin(), v.end(), greater<pair<int, int> >());
    int tar = n - 1;
    priority_queue<int, vector<int>, greater<int> > pq;
    long long int ans = 0;
    for (int i = 0; i < n; i++) {
      pq.push(v[i].second);
      if (tar < v[i].first) {
        ans += pq.top();
        pq.pop();
      } else
        tar--;
    }
    cout << ans << "\n";
  }
}
