#include <bits/stdc++.h>
using namespace std;
int main() {
  int test;
  cin >> test;
  while (test--) {
    int n;
    cin >> n;
    vector<pair<int, int>> per(n);
    for (int i = 0; i < n; i++) {
      cin >> per[i].first >> per[i].second;
    }
    sort(per.begin(), per.end());
    int prefix[n + 1];
    prefix[0] = 0;
    int j = 0;
    for (int i = 1; i < n; i++) {
      prefix[i] = prefix[i - 1];
      while (per[j].first == i - 1) {
        prefix[i]++;
        j++;
      }
    }
    int cnt = 0;
    long long cost = 0;
    priority_queue<int, vector<int>, greater<int>> pq;
    for (int i = n - 1; i >= 0; i--) {
      if (prefix[per[i].first] + cnt >= per[i].first) {
        pq.push(per[i].second);
        continue;
      }
      int tmp = per[i].first - cnt - prefix[per[i].first];
      int j = i;
      while (per[j].first == per[i].first) {
        pq.push(per[j].second);
        j--;
      }
      i = j + 1;
      while (tmp--) {
        cnt++;
        cost += pq.top();
        pq.pop();
      }
    }
    cout << cost << "\n";
  }
}
