#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 15;
pair<int, int> in[N];
void solve2() {
  int n;
  scanf("%d ", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d %d ", &in[i].first, &in[i].second);
  }
  sort(in, in + n);
  long long ret = 0;
  priority_queue<int, vector<int>, greater<int> > pq;
  int num = 0;
  for (int i = n - 1; i >= 0;) {
    int j;
    for (j = i; j >= 0; --j) {
      if (in[j].first != in[i].first) break;
      pq.push(in[j].second);
    }
    while (num + j + 1 < in[i].first) {
      assert(!pq.empty());
      ++num;
      ret += pq.top();
      pq.pop();
    }
    i = j;
  }
  printf("%lld\n", ret);
}
void solve() {
  int t;
  scanf("%d", &t);
  while (t--) solve2();
}
inline bool exists_test0(const std::string& name);
inline bool exists_test1(const std::string& name);
int main() {
  solve();
  return 0;
}
inline bool exists_test0(const std::string& name) {
  ifstream f(name.c_str());
  return f.good();
}
inline bool exists_test1(const std::string& name) {
  if (FILE* file = fopen(name.c_str(), "r")) {
    fclose(file);
    return true;
  } else {
    return false;
  }
}
