#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<ll, ll>;
int main(int argc, char **argv) {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int tc;
  cin >> tc;
  while (tc--) {
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
    for (int i = 0; i < n; i++) {
      if (a[i] == 0) b[i] = 0;
    }
    vector<vector<int>> ids(n);
    for (int i = 0; i < n; i++) {
      ids[a[i]].push_back(i);
    }
    for (int i = 0; i < n; i++) {
      sort(ids[i].begin(), ids[i].end(),
           [&](int x, int y) { return b[x] < b[y]; });
    }
    ll res = 1e18;
    for (int th = 0; th <= n; th++) {
      ll t = 0;
      int cur = 0;
      vector<int> used(n, false);
      vector<int> l;
      for (int i = 0; i < n; i++) {
        if (a[i] >= th) {
          l.push_back(i);
        }
      }
      sort(l.begin(), l.end(), [&](int x, int y) { return b[x] < b[y]; });
      int pi = 0;
      for (int x : l) {
        if (used[x]) continue;
        used[x] = true;
        cur++;
        t += b[x];
        while (pi < n && ids[pi].size() == 0) {
          pi++;
        }
        while (pi < n && pi <= cur) {
          for (int y : ids[pi]) {
            if (used[y]) continue;
            cur++;
            used[y] = true;
          }
          pi++;
        }
      }
      if (cur == n) res = min(res, t);
    }
    cout << res << '\n';
  }
  return 0;
}
