#include <bits/stdc++.h>
using namespace std;
pair<int, int> v[200005];
bool voted[200005];
set<pair<int, int>> s;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      v[i] = make_pair(m, -p);
    }
    sort(v, v + n);
    s.clear();
    for (int i = 0; i < n; i++) {
      v[i].second *= -1;
      s.insert(make_pair(v[i].second, i));
      voted[i] = false;
    }
    int vote = 0;
    long long cost = 0;
    for (int i = 0; i < n; i++) {
      if (voted[i]) continue;
      s.erase(s.find(make_pair(v[i].second, i)));
      while (vote < v[i].first) {
        auto temp = s.begin();
        cost += temp->first;
        vote++;
        voted[temp->second] = true;
        s.erase(temp);
      }
      vote++;
      voted[i] = true;
    }
    cout << cost << endl;
  }
}
