#include <bits/stdc++.h>
using namespace std;
int cmp(pair<int, int> a, pair<int, int> b) { return a.first < b.first; }
int main() {
  ios::sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) {
    int n;
    cin >> n;
    vector<pair<int, int> > all(n);
    map<int, int> va;
    vector<int> visit(n, 0);
    for (int i(0); i < n; i++) {
      cin >> all[i].first >> all[i].second;
      va[all[i].first] = va[all[i].first] + 1;
    }
    sort(all.begin(), all.end(), cmp);
    long long ans(0), ct(0);
    for (int i(0); i < n; i++) {
      if (visit[i] == 1) {
        ct++;
        continue;
      }
      while (ct < all[i].first) {
        int j;
        if (va[all[i].first] != 1)
          j = i;
        else
          j = i + 1;
        int index = j;
        for (; j < n; j++) {
          if (all[j].second <= all[index].second && visit[j] == 0 ||
              visit[index] == 1) {
            index = j;
          }
        }
        ct += 1;
        ans += all[index].second;
        visit[index] = 1;
      }
      ct++;
    }
    cout << ans << endl;
  }
  return 0;
}
