#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    pair<int, int> a[n];
    for (int i = 0; i < n; i++) {
      scanf("%d%d", &a[i].first, &a[i].second);
    }
    sort(a, a + n);
    priority_queue<int, vector<int>, greater<int> > pq;
    int taken = 0;
    long long ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      pq.push(a[i].second);
      if (i == 0 || a[i].first != a[i - 1].first) {
        int num = max(0, (a[i].first - i) - taken);
        taken += num;
        while (num-- && pq.size()) {
          ans += pq.top();
          pq.pop();
        }
      }
    }
    printf("%lld\n", ans);
  }
}
