#include <bits/stdc++.h>
using namespace std;
int const MAXN = 2e6 + 9;
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<vector<int>> g(n + 1);
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      g[m].push_back(p);
    }
    int pref = n;
    long long ans = 0;
    int cur = 0;
    multiset<int> st;
    for (int i = n; i >= 0; i--) {
      pref -= (int)g[i].size();
      for (auto x : g[i]) st.insert(x);
      int need = 0;
      if (pref + cur < i) need = i - pref - cur, cur += need;
      while (need) {
        need--;
        ans += *st.begin();
        st.erase(st.begin());
      }
    }
    cout << ans << '\n';
  }
}
