#include <bits/stdc++.h>
using namespace std;
template <typename _T>
inline void _DBG(const char *s, _T x) {
  cerr << s << " = " << x << "\n";
}
template <typename _T, typename... args>
void _DBG(const char *s, _T x, args... a) {
  while (*s != ',') cerr << *s++;
  cerr << " = " << x << ',';
  _DBG(s + 1, a...);
}
struct SegmentTree {
  const static int MAX = 1 << 18;
  long long INF = 1e18 + 7;
  vector<pair<long long, long long> > tree;
  vector<long long> lazy;
  SegmentTree() {
    tree.resize(2 * MAX, {0, 0}), lazy.resize(2 * MAX, 0);
    for (int i = 0; i <= MAX - 1; i++) tree[i + MAX].second = i;
    for (int i = MAX - 1; i; i--) tree[i] = min(tree[2 * i], tree[2 * i + 1]);
  }
  inline void propagate(int node, int l, int r) {
    if (!lazy[node]) return;
    tree[node].first += lazy[node];
    if (l != r) {
      lazy[2 * node] += lazy[node];
      lazy[2 * node + 1] += lazy[node];
    }
    lazy[node] = 0;
  }
  void update(int a, int b, long long val, int node = 1, int l = 0,
              int r = MAX - 1) {
    propagate(node, l, r);
    if (b < l || r < a) return;
    if (a <= l && r <= b)
      lazy[node] += val, propagate(node, l, r);
    else {
      update(a, b, val, 2 * node, l, (l + r) / 2);
      update(a, b, val, 2 * node + 1, (l + r) / 2 + 1, r);
      tree[node] = min(tree[2 * node], tree[2 * node + 1]);
    }
  }
  pair<long long, long long> query(int a, int b, int node = 1, int l = 0,
                                   int r = MAX - 1) {
    propagate(node, l, r);
    if (b < l || r < a) return {INF, 0};
    if (a <= l && r <= b) return tree[node];
    return min(query(a, b, 2 * node, l, (l + r) / 2),
               query(a, b, 2 * node + 1, (l + r) / 2 + 1, r));
  }
};
const int N = 2e5 + 7;
int n, pre[N];
SegmentTree tree;
vector<int> use[N];
void solve() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    pre[i] = -1;
    use[i].clear();
  }
  for (int i = 1; i <= n; i++) {
    int x, p;
    cin >> x >> p;
    x++;
    use[x].push_back(p);
    pre[x]++;
  }
  for (int i = 1; i <= n; i++) {
    if (i > 1) pre[i] += pre[i - 1];
    tree.update(i, i, pre[i]);
  }
  long long ans = 0;
  priority_queue<pair<int, int> > Q;
  for (int i = n; i; i--) {
    auto p = tree.query(i, i);
    while (p.first < 0) {
      assert(!Q.empty());
      pair<int, int> q = Q.top();
      Q.pop();
      ans += -q.first;
      tree.update(1, q.second - 1, 1);
      p = tree.query(i, i);
    }
    for (auto q : use[i]) Q.push({-q, i});
  }
  cout << ans << "\n";
  for (int i = 1; i <= n; i++) tree.update(i, i, -tree.query(i, i).first);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
