#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> voters(200000);
struct classcomp {
  bool operator()(const int& a, const int& b) const {
    if (voters[a].second < voters[b].second) {
      return true;
    } else if (voters[a].second > voters[b].second) {
      return false;
    }
    return a < b;
  }
};
int comp(int a, int b) { return voters[a].second < voters[b].second; }
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  for (int z = 0; z < t; z++) {
    int n;
    cin >> n;
    vector<int> arr(n, 0);
    vector<int> past(n);
    vector<vector<int>> sets(n);
    vector<int> srt;
    for (int i = 0; i < n; i++) {
      int m, p;
      cin >> m >> p;
      voters[i] = make_pair(m, p);
      sets[m].push_back(i);
      arr[m]++;
    }
    int last = n;
    int count = 0;
    for (int i = n - 1; i >= 0; i--) {
      count++;
      if (sets[i].empty()) {
        past[i] = 0;
        continue;
      }
      if (sets[i].size() >= count) {
        past[i] = sets[i].size() - count;
        count = 0;
        last = i;
      } else {
        count -= sets[i].size();
        past[i] = 0;
      }
    }
    set<int, classcomp> use;
    for (int i = last; i < n; i++) {
      sort(sets[i].begin(), sets[i].end(), comp);
      for (int a = 0; a < past[i]; a++) {
        use.insert(sets[i][a]);
      }
      count = past[i];
      while (!use.empty() && count < sets[i].size() &&
             voters[sets[i][count]].second < voters[*(--use.end())].second) {
        use.erase(--use.end());
        use.insert(sets[i][count]);
        count++;
      };
    }
    long long sum = 0;
    for (int i : use) {
      sum += voters[i].second;
    }
    cout << sum << "\n";
  }
}
