#include <bits/stdc++.h>
using namespace std;
pair<int, int> a[300005];
int b[300005];
set<int> s;
int main() {
  int q;
  scanf("%d", &q);
  while (q--) {
    s.clear();
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
      scanf("%d%d", &a[i].first, &a[i].second);
    }
    sort(a, a + n);
    for (int i = 0; i < n; i++) {
      if (a[i].first > i) {
        b[i] = a[i].first - i;
      }
    }
    int br = 0;
    long long sol = 0;
    for (int i = n - 1; i >= 0; i--) {
      s.insert(a[i].second);
      while (br < b[i] and s.size()) {
        br++;
        sol += (long long)*s.begin();
        s.erase(s.begin());
      }
    }
    printf("%I64d\n", sol);
    for (int i = 0; i < n; i++) {
      b[i] = 0;
    }
  }
  return 0;
}
