#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
bool cmp(pair<int, int> rh1, pair<int, int> rh2) {
  if (rh1.first == rh2.first)
    return rh1.second > rh2.second;
  else
    return rh1.first < rh2.first;
}
bool cmp2(pair<int, int> rh1, pair<int, int> rh2) {
  return rh1.second < rh2.second;
}
int r[N];
int cnt[N];
pair<int, int> dat[N];
void solve() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i <= n + 5; i++) r[i] = cnt[i] = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &dat[i].first, &dat[i].second);
    cnt[dat[i].first]++;
  }
  for (int i = 1; i <= n; i++) cnt[i] += cnt[i - 1];
  r[n] = n;
  int mi;
  for (int i = n - 1; i >= 0; i--) {
    int s = cnt[i];
    int j = i;
    while (s > j) {
      j = s;
      s = r[s];
    }
    r[i] = j;
  }
  for (int i = 0; i < n; i++)
    if (r[i] == n) {
      mi = i;
      break;
    }
  long long ans = 0;
  sort(dat + 1, dat + n + 1, cmp2);
  for (int i = 1; i <= mi; i++) ans += dat[i].second;
  sort(dat + 1, dat + n + 1, cmp);
  long long t = 0;
  int cur = 0;
  int L = 1;
  multiset<int> st;
  for (int i = 1; i <= n; i++) st.insert(dat[i].second);
  for (int i = n; i >= 1; i--) {
    t += dat[i].second;
    cur++;
    st.erase(st.lower_bound(dat[i].second));
    int R = i - 1;
    while (L <= R && dat[L].first <= r[cur]) {
      st.erase(st.lower_bound(dat[L].second));
      L++, cur++;
    }
    vector<int> vec;
    while (cur < mi && r[cur] < dat[R].first) {
      vec.push_back(*st.begin());
      st.erase(st.begin());
      cur++;
    }
    long long tt = t;
    for (auto j : vec) tt += j, st.insert(j);
    cur -= (int)vec.size();
    ans = min(ans, tt);
    if (L > R) break;
  }
  printf("%lld\n", ans);
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) solve();
  return 0;
}
