#include <bits/stdc++.h>
class Solve {
 private:
 public:
  Solve() {
    int n;
    scanf("%d", &n);
    std::vector<std::vector<int64_t>> voters(n);
    int bought{};
    int64_t cost{};
    for (int i{}; i < n; i++) {
      int m;
      int64_t p;
      scanf("%d%lld", &m, &p);
      if (m == 0)
        bought++;
      else if (m == n) {
        bought++;
        cost += p;
      } else
        voters[m].push_back(p);
    }
    std::priority_queue<int64_t, std::vector<int64_t>, std::greater<int64_t>>
        pq;
    int saw{};
    for (int i{n - 1}; i > 0; i--) {
      for (auto& e : voters[i]) {
        pq.push(e);
        saw++;
      }
      while (n - saw + bought < i) {
        cost += pq.top();
        pq.pop();
        bought++;
      }
    }
    printf("%lld\n", cost);
  }
};
int main() {
  int t;
  scanf("%d", &t);
  for (int i{}; i < t; i++) Solve();
  return 0;
}
