#include <bits/stdc++.h>
const int N = 5000;
int t, n;
std::pair<int, int> a[N];
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) scanf("%d%d", &a[i].first, &a[i].second);
    std::sort(a, a + n);
    int i = 0;
    std::vector<std::pair<int, int> > r;
    while (i < n) {
      while (i < n && i >= a[i].first) ++i;
      if (i < n) {
        r.push_back(std::make_pair(i, a[i].first - i));
        do {
          ++i;
        } while (i < n && a[i].first == a[r.back().first].first);
      }
    }
    int last = n, amt = 0;
    std::set<int> s;
    long long ans = 0;
    for (int i = (int)r.size() - 1; i >= 0; --i) {
      for (int j = r[i].first; j < last; ++j) s.insert(a[j].second);
      while (r[i].second > amt) {
        ans += *s.begin();
        ++amt;
        s.erase(s.begin());
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
