#include <bits/stdc++.h>
using namespace std;
const long long N = 5001;
pair<long long, long long> mp[N];
void solve() {
  long long n;
  cin >> n;
  long long x, y;
  for (long long i = 1; i <= n; i++) {
    cin >> x >> y;
    mp[i] = {x, y};
  }
  sort(mp + 1, mp + n + 1);
  long long ans = 0;
  priority_queue<long long, vector<long long>, greater<long long> > price;
  long long extra = 0;
  for (long long i = n; i > 0; i--) {
    long long m = mp[i].first;
    while (i > 0 && mp[i].first == m) {
      price.push(mp[i].second);
      i--;
    }
    i++;
    long long need = m - (i - 1 + extra);
    if (need <= 0) continue;
    while (need--) {
      extra++;
      ans += price.top();
      price.pop();
    }
  }
  cout << ans << endl;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
