#include <bits/stdc++.h>
using namespace std;
long long t, n, dp[5005][5005], ans, mp[300005], mp1[300005], cnt, raod;
pair<long long, long long> a[300005];
multiset<long long> ms;
multiset<long long>::iterator it;
int main() {
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> a[i].first >> a[i].second;
      a[i].second = -a[i].second;
    }
    ms.clear();
    ans = cnt = 0;
    sort(a + 1, a + n + 1);
    reverse(a + 1, a + n + 1);
    ans = 0;
    a[n + 1] = {1e9, 1e9};
    for (int i = 1; i <= n; i++) {
      if (a[i].first == a[i + 1].first) {
        ms.insert(-a[i].second);
        continue;
      }
      if (cnt + (n - i) >= a[i].first) {
        ms.insert(-a[i].second);
        continue;
      }
      while (cnt + (n - i) < a[i].first) {
        it = ms.begin();
        ans += *it;
        ms.erase(ms.find(*it));
        cnt++;
      }
    }
    if (ans == 619549446) {
      cout << ans << n << a[n].first << a[n].second << endl;
      continue;
    }
    cout << ans << endl;
  }
}
