#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18 + 7;
const int mod = 1e9 + 7;
const int N = 2e6 + 7;
long long n, m, k, a, b, c, d, q;
long long ans, cur, sum, cnt;
long long ar[N], pre[N];
map<long long, long long> mp;
vector<long long> v;
string str;
struct person {
  long long cost, vote;
  bool operator<(person const &a) const { return vote < a.vote; }
};
person p[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> q;
  while (q--) {
    priority_queue<long long, vector<long long>, greater<long long> > pq;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> p[i].vote >> p[i].cost;
    sort(p + 1, p + n + 1);
    for (int i = n; i >= 1; i--) {
      pq.push(p[i].cost);
      if (p[i].vote <= cnt + i - 1) continue;
      ans += pq.top();
      pq.pop();
      cnt++;
    }
    cout << ans << '\n';
    ans = cnt = 0;
  }
}
