#include <bits/stdc++.h>
using namespace std;
int n;
vector<bool> voted;
vector<pair<pair<int, int>, int> > voters;
int voted_count;
set<pair<int, int> > remaining_voters;
long long answer;
bool cmp(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {
  return make_pair(a.first.first, -a.first.second) <
         make_pair(b.first.first, -b.first.second);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int tc;
  cin >> tc;
  while (tc--) {
    cin >> n;
    voted.assign(n, false);
    voters.assign(n, {{0, 0}, -1});
    remaining_voters.clear();
    voted_count = 0;
    answer = 0;
    for (int i = 0; i < n; i++) {
      cin >> voters[i].first.first;
      cin >> voters[i].first.second;
      voters[i].second = i;
    }
    sort(voters.begin(), voters.end(), cmp);
    bool flag = false;
    for (int i = 0; i < n; i++) {
      if (!flag) {
        if (voted_count >= voters[i].first.first) {
          voted_count++;
          voted[voters[i].second] = true;
        } else {
          flag = true;
          remaining_voters.insert({voters[i].first.second, voters[i].second});
        }
      } else {
        remaining_voters.insert({voters[i].first.second, voters[i].second});
      }
    }
    for (int i = 0; i < n; i++) {
      if (!voted[voters[i].second]) {
        auto it = remaining_voters.begin();
        pair<int, int> top = {0, -1};
        while (it != remaining_voters.end()) {
          top = *it;
          remaining_voters.erase(it);
          if (!voted[top.second] && top.second != voters[i].second) break;
          it = remaining_voters.begin();
        }
        if (top.second != -1) {
          voted[top.second] = true;
          voted_count++;
          answer += top.first;
        } else {
          voted[voters[i].second] = true;
          voted_count++;
          answer += voters[i].first.second;
          i++;
        }
        while (i < n) {
          if (voted[voters[i].second]) {
            i++;
            continue;
          }
          if (voters[i].first.first <= voted_count) {
            i++;
            voted_count++;
          } else
            break;
        }
        i--;
      }
    }
    cout << answer << "\n";
  }
  return 0;
}
