#include <bits/stdc++.h>
long long minCost(std::vector<long>& swayThreshold,
                  std::vector<long>& bribePrice) {
  long n = swayThreshold.size();
  std::vector<std::vector<long>> votersWithSwayThreshold(n,
                                                         std::vector<long>{});
  std::vector<long> numWithThreshold(n, 0);
  for (int i = 0; i < n; ++i) {
    votersWithSwayThreshold[swayThreshold[i]].push_back(bribePrice[i]);
    ++numWithThreshold[swayThreshold[i]];
  }
  std::vector<long> numWithThresholdLessThan(n, 0);
  long temp = 0;
  for (int i = 0; i < n; ++i) {
    numWithThresholdLessThan[i] = temp;
    temp += numWithThreshold[i];
  }
  std::multiset<long> availablePrices{};
  long boughtSoFar = 0;
  long long spentSoFar = 0;
  for (long threshold = n - 1; threshold >= 0; --threshold) {
    long numWithThisThreshold = numWithThreshold[threshold];
    if (numWithThisThreshold > 0) {
      for (long price : votersWithSwayThreshold[threshold]) {
        availablePrices.insert(price);
      }
      if (boughtSoFar + numWithThresholdLessThan[threshold] >= threshold) {
      } else {
        long needToBuy =
            threshold - boughtSoFar - numWithThresholdLessThan[threshold];
        for (int i = 0; i < needToBuy; ++i) {
          spentSoFar += *(availablePrices.begin());
          availablePrices.erase(availablePrices.begin());
        }
        boughtSoFar += needToBuy;
      }
    }
  }
  return spentSoFar;
}
int main() {
  int t;
  std::cin >> t;
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  for (int q = 0; q < t; ++q) {
    int n;
    std::cin >> n;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::vector<long> swayThreshold(n), bribePrice(n);
    for (int i = 0; i < n; ++i) {
      std::cin >> swayThreshold[i] >> bribePrice[i];
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << minCost(swayThreshold, bribePrice);
  }
  return 0;
}
