#include <bits/stdc++.h>
using namespace std;
using INT = long long;
using pii = pair<int, int>;
const int NN = 272727;
pii p[NN];
multiset<int> st;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d%d", &p[i].first, &p[i].second);
    sort(p + 1, p + n + 1);
    int val = 0;
    INT ans = 0;
    for (int i = n; i;) {
      int u = p[i].first;
      while (p[i].first == u and i) st.insert(p[i].second), i--;
      if (val + i >= u) continue;
      int N = u - val - i;
      val += N;
      while (N--) {
        int it = (*st.begin());
        ans += it;
        st.erase(st.begin());
      }
    }
    cout << ans << endl;
    st.clear();
  }
  return 0;
}
