#include <bits/stdc++.h>
using namespace std;
void build_segment_tree(vector<pair<int, int> > &tree, int node, int b, int e,
                        vector<pair<int, int> > &v) {
  if (b == e) {
    tree[node] = make_pair(v[b].second, b);
    return;
  }
  int m = b + (e - b) / 2;
  build_segment_tree(tree, 2 * node + 1, b, m, v);
  build_segment_tree(tree, 2 * node + 2, m + 1, e, v);
  pair<int, int> left = tree[2 * node + 1];
  pair<int, int> right = tree[2 * node + 2];
  if (right < left)
    tree[node] = right;
  else
    tree[node] = left;
}
void update(vector<pair<int, int> > &tree, int node, int b, int e, int idx) {
  if (b == e && b == idx) {
    tree[node] = make_pair(INT_MAX, INT_MAX);
    return;
  }
  if (idx < b || e < idx) return;
  int m = b + (e - b) / 2;
  update(tree, 2 * node + 1, b, m, idx);
  update(tree, 2 * node + 2, m + 1, e, idx);
  pair<int, int> p;
  p.first = min(tree[2 * node + 1].first, tree[2 * node + 2].first);
  p.second = tree[2 * node + 1].second;
  if (p.first == tree[2 * node + 2].first) {
    p.second = tree[2 * node + 2].second;
  }
  tree[node] = p;
}
pair<int, int> query(vector<pair<int, int> > &tree, int node, int b, int e,
                     int l, int r) {
  if (r < b || e < l) return make_pair(INT_MAX, INT_MAX);
  if (l <= b && e <= r) return tree[node];
  int m = b + (e - b) / 2;
  pair<int, int> left = query(tree, 2 * node + 1, b, m, l, r);
  pair<int, int> right = query(tree, 2 * node + 2, m + 1, e, l, r);
  if (left < right) return left;
  return right;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<int, int> > v(n);
    for (int i = 0; i < n; i++) {
      pair<int, int> p;
      cin >> p.first >> p.second;
      v[i] = p;
    }
    sort(v.begin(), v.end());
    long long int sum = 0;
    vector<pair<int, int> > tree(4 * n);
    build_segment_tree(tree, 0, 0, n - 1, v);
    int count = 0;
    for (int i = n - 1; i >= 0; i--) {
      while (v[i].first > i + count) {
        pair<int, int> p = query(tree, 0, 0, n - 1, i, n - 1);
        sum = sum + p.first;
        update(tree, 0, 0, n - 1, p.second);
        count++;
      }
    }
    cout << sum << endl;
  }
  return 0;
}
