#include <bits/stdc++.h>
using namespace std;
void solveFunction() {
  int n;
  cin >> n;
  map<int, vector<int>> mp;
  map<int, vector<int>>::reverse_iterator it;
  for (int i = 0; i < n; i++) {
    int m, p;
    cin >> m >> p;
    mp[m].push_back(p);
  }
  for (auto i : mp)
    sort(mp[i.first].begin(), mp[i.first].end(), greater<int>());
  int cnt = 0;
  long long int sum = 0;
  if (mp.find(0) != mp.end()) {
    cnt += mp[0].size();
    mp.erase(0);
  }
  map<int, int> prefix;
  int previous = 0;
  for (auto i : mp) {
    prefix[i.first] = i.second.size() + previous;
    previous = prefix[i.first];
  }
  multiset<pair<int, int>> st;
  for (it = mp.rbegin(); it != mp.rend(); it++) {
    int tot = prefix[it->first] - it->second.size() + cnt;
    int req = it->first - tot;
    for (auto i : mp[it->first]) st.insert({i, it->first});
    while (req > 0) {
      pair<int, int> x = *st.begin();
      st.erase(st.lower_bound(x));
      sum += x.first;
      mp[x.second].pop_back();
      cnt++;
      req--;
    }
  }
  while (1) {
    int prevCnt = cnt, mn = INT_MAX, mnid;
    bool flag = false;
    for (auto i : mp) {
      if (i.second.size() > 0) flag = true;
      if (i.second.size() > 0 && i.first <= cnt) {
        cnt += i.second.size();
        mp[i.first].clear();
      } else if (i.second.size() > 0 && i.second.back() < mn) {
        mn = i.second.back();
        mnid = i.first;
      }
    }
    if (!flag) break;
    if (cnt == prevCnt) {
      cnt++;
      sum += mn;
      mp[mnid].pop_back();
    }
  }
  cout << sum << "\n";
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t = 1;
  cin >> t;
  while (t--) {
    solveFunction();
  }
}
