#include <bits/stdc++.h>
using namespace std;
const int MAX_NUM = 200005;
struct Info {
  int m, p;
  bool operator<(const Info& o) const {
    if (m != o.m) {
      return m < o.m;
    }
    return p > o.p;
  }
} info[MAX_NUM];
priority_queue<int, vector<int>, greater<int> > heap;
int main() {
  int test_case;
  scanf("%d", &test_case);
  while (test_case--) {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
      scanf("%d%d", &info[i].m, &info[i].p);
    }
    while (heap.size() > 0) heap.pop();
    sort(info, info + n);
    int cost = 0, purchased = 0;
    for (int i = n - 1; i >= 0; i--) {
      heap.push(info[i].p);
      for (int j = 0; j < info[i].m - i - purchased; j++) {
        cost += heap.top();
        heap.pop();
      }
      purchased += max(0, info[i].m - i - purchased);
    }
    printf("%d\n\n", cost);
  }
  return 0;
}
