#include <bits/stdc++.h>
using namespace std;
template <class T>
inline T bigmod(T b, T p, T M) {
  long long int ret = 1;
  for (; p > 0; p >>= 1) {
    if (p & 1) ret = (ret * b) % M;
    b = (b * b) % M;
  }
  return (T)ret;
}
template <class T>
inline T modinverse(T a, T M) {
  return bigmod(a, M - 2, M);
}
template <class T>
inline T gcd(T a, T b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
template <class T>
inline T lcm(T a, T b) {
  return a * b / gcd<T>(a, b);
}
template <class T>
inline T power(T b, T p) {
  long long int x = 1;
  while (p--) x *= b;
  return x;
}
const long long int mod = 1e9 + 9;
const int siz = 200005;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> need, cost[n + 5];
    priority_queue<int, vector<int>, greater<int> > pq;
    for (int i = 1; i <= n; i++) {
      int m, p;
      cin >> m >> p;
      need.push_back(m), cost[m].push_back(p);
    }
    sort(need.begin(), need.end()),
        need.erase(unique(need.begin(), need.end()), need.end());
    long long int yet = 0, ans = 0, buy = 0;
    for (int i = need.size() - 1; i >= 0; i--) {
      for (auto x : cost[need[i]]) yet++, pq.push(x);
      int notYet = n - yet + buy;
      while (notYet < need[i]) {
        ans += pq.top();
        pq.pop();
        need[i]--, buy++;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
