#include <bits/stdc++.h>
using namespace std;
long long res = 0;
int T, N;
vector<pair<int, int>> v;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
    mn;
priority_queue<int> del;
bool chk[200201];
int main() {
  scanf("%d", &T);
  while (T--) {
    res = 0;
    v.clear();
    while (!mn.empty()) mn.pop();
    scanf("%d", &N);
    v.resize(N);
    for (int i = 0; i < N; i++) chk[i] = false;
    for (int i = 0; i < N; i++) scanf("%d %d", &v[i].first, &v[i].second);
    sort(v.begin(), v.end());
    for (int i = 0; i < N; i++) mn.push({v[i].second, i});
    int i = 0, cnt = 0;
    while (i < N) {
      while (cnt < v[i].first) {
        int val = mn.top().first, idx = mn.top().second;
        mn.pop();
        if (chk[idx]) continue;
        chk[idx] = true;
        cnt++;
        res += val;
      }
      while (1) {
        while (i < N && cnt >= v[i].first) {
          if (chk[i])
            del.push(i);
          else
            cnt++;
          chk[i] = true;
          i++;
        }
        if (del.empty() || i == N) break;
        while (!del.empty()) {
          int j = del.top();
          del.pop();
          int success = 0;
          while (success == 0 && !mn.empty()) {
            int val = mn.top().first, idx = mn.top().second;
            mn.pop();
            if (chk[idx]) continue;
            chk[idx] = true;
            success = 1;
            cnt++;
            res += val;
          }
          if (success) {
            res -= v[j].second;
          }
        }
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
