#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  tuple<long long, long long> ps[300005];
  for (int _ = 0; _ < t; _++) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      ps[i] = make_tuple(m, -p);
    }
    sort(ps, ps + n);
    priority_queue<long long> fr;
    int cn = 0;
    long long pr = 0;
    long long dbt = 0;
    for (int i = 0; i < n; i++) {
      long long cm, cp;
      tie(cm, cp) = ps[i];
      if (cm == cn) {
        cn++;
        fr = priority_queue<long long>();
      } else if (cm < cn) {
        fr.push(cp);
        cn++;
      } else {
        dbt += cm - cn;
        cn = cm + 1;
        fr = priority_queue<long long>();
      }
    }
    for (int i = 0; i < dbt; i++) {
      pr -= fr.top();
      fr.pop();
    }
    cout << pr << endl;
  }
  return 0;
}
