#include <bits/stdc++.h>
using namespace std;
const int Mod = (int)1e9 + 7;
const int MX = 1073741822;
const long long MXLL = 4e18;
const int Sz = 1110111;
inline void Read_rap() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
inline void randomizer3000() {
  unsigned int seed;
  asm("rdtsc" : "=A"(seed));
  srand(seed);
}
void files(string problem) {
  if (fopen((problem + ".in").c_str(), "r")) {
    freopen((problem + ".in").c_str(), "r", stdin);
    freopen((problem + ".out").c_str(), "w", stdout);
  }
}
void localInput(const char in[] = "s") {
  if (fopen(in, "r")) {
    freopen(in, "r", stdin);
  } else if (0)
    cout << "Warning: Input file not found" << endl;
}
vector<int> g[Sz];
int main() {
  Read_rap();
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) g[i].clear();
    for (int i = 1; i <= n; i++) {
      int x, y;
      cin >> x >> y;
      g[x].push_back(y);
    }
    int b = 0;
    int l = 0;
    int r = 0;
    long long ans = 0;
    multiset<int> st;
    for (int i = n; i >= 1; i--) {
      for (int x : g[i]) st.insert(x);
      r += (int)(g[i].size());
      if (b + n - r < i) {
        int x = i - (n - r + b);
        for (int j = 0; j < x; j++) {
          ans += *st.begin();
          st.erase(st.begin());
        }
        b += x;
        r -= x;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
