#include <bits/stdc++.h>
using namespace std;
const int maxn = 200003;
int n;
pair<int, int> a[maxn];
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].first, &a[i].second);
    sort(a + 1, a + n + 1);
    long long ans = 0;
    int cur = 0;
    priority_queue<pair<int, int>, vector<pair<int, int> >,
                   greater<pair<int, int> > >
        q;
    for (int i = n; i >= 1; i--) {
      q.push(pair<int, int>(a[i].second, i));
      while (a[i].first > i - 1 + cur) {
        pair<int, int> tp = q.top();
        q.pop();
        ans += tp.first;
        cur++;
        if (tp.second == i) break;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
