#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
inline void chmin(T1 &a, T2 b) {
  if (a > b) a = b;
}
template <typename T1, typename T2>
inline void chmax(T1 &a, T2 b) {
  if (a < b) a = b;
}
const long long MOD = 1e9 + 7;
const long long MAX = 200060;
const double pi = acos(-1);
const long long INF = 1e16;
template <typename T>
struct edge {
  long long src, to;
  T cost;
  edge(long long to, T cost) : src(-1), to(to), cost(cost) {}
  edge(long long src, long long to, T cost) : src(src), to(to), cost(cost) {}
  edge &operator=(const long long &x) {
    to = x;
    return *this;
  }
  operator long long() const { return to; }
};
template <typename T>
using Edges = vector<edge<T> >;
template <typename T>
using WeightedGraph = vector<Edges<T> >;
using UnWeightedGraph = vector<vector<long long> >;
template <typename T>
using Matrix = vector<vector<T> >;
void solve() {
  long long N;
  cin >> N;
  vector<pair<long long, long long> > v(N);
  vector<long long> dp(N + 1);
  for (long long i = 0; i < N; i++) {
    long long n;
    cin >> n;
    long long A;
    cin >> A;
    v[i] = {n, A};
  }
  sort(v.begin(), v.end());
  ;
  for (long long i = 0; i < N + 1; i++) dp[i] = INF;
  dp[0] = 0;
  priority_queue<long long> que;
  bool flag = false;
  que.push(0);
  for (long long i = 0; i < N; i++) {
    if (i >= v[i].first) {
      long long res = 0;
      if (flag) {
        res = dp[i] + v[i].second - que.top();
      } else {
        res = dp[i] + v[i].second;
      }
      if (res <= dp[i]) {
        que.push(v[i].second);
        if (flag) que.pop();
        dp[i + 1] = res;
      } else
        dp[i + 1] = dp[i];
    } else {
      long long res = 0;
      if (flag) {
        res = dp[i] + v[i].second - que.top();
      } else {
        res = dp[i] + v[i].second;
      }
      que.push(v[i].second);
      if (flag) que.pop();
      dp[i + 1] = res;
    }
    if (i + 1 >= v[i].first) flag = true;
  }
  cout << dp[N] << '\n';
  ;
}
signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long long Q;
  cin >> Q;
  while (Q--) solve();
}
