#include <bits/stdc++.h>
using namespace std;
const int N = 200002 + 1;
const int MOD = 1000000007;
const long long MAX = 10000000000;
const int oo = 1e9;
int t, n;
vector<int> g[5001];
int main() {
  cin >> t;
  while (t--) {
    scanf("%d", &n);
    for (int a, b, i = 0; i < n; ++i) {
      scanf("%d%d", &a, &b);
      g[a].push_back(b);
    }
    multiset<int> st;
    int buy = 0, rem = n;
    long long ans = 0;
    for (int i = n; i >= 0; --i) {
      if (g[i].size() == 0) continue;
      rem -= g[i].size();
      for (auto v : g[i]) st.insert(v);
      int need = max(0, i - rem - buy);
      while (need--) {
        buy++;
        ans += *st.begin();
        st.erase(st.begin());
      }
    }
    printf("%lld\n", ans);
    for (int i = 0; i <= n; ++i) g[i].clear();
  }
  return 0;
}
