#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n;
int num[N], val[N], nid[N], _nid[N], vid[N], ed[N];
bool vot[N];
struct SEGTREE {
  inline int idx(const int& l, const int& r) { return (l + r) | (l != r); }
  pair<int, int> key[N << 1];
  void Build(const int& le, const int& ri) {
    if (le == ri) {
      key[idx(le, ri)] = make_pair(-1, 0);
      return;
    }
    int mi = (le + ri) >> 1;
    Build(le, mi), Build(mi + 1, ri);
    key[idx(le, ri)] = max(key[idx(le, mi)], key[idx(mi + 1, ri)]);
  }
  pair<int, int> Query(const int& le, const int& ri, const int& Ri) {
    if (!Ri) return make_pair(-1, 0);
    if (ri <= Ri) return key[idx(le, ri)];
    int mi = (le + ri) >> 1;
    if (Ri <= mi) return Query(le, mi, Ri);
    return max(key[idx(le, mi)], Query(mi + 1, ri, Ri));
  }
  void Modify(const int& le, const int& ri, const int& pos, bool typ) {
    if (le == ri) {
      if (typ)
        key[idx(le, ri)] = make_pair(val[nid[le]], le);
      else
        key[idx(le, ri)] = make_pair(-1, 0);
      return;
    }
    int mi = (le + ri) >> 1;
    if (pos <= mi)
      Modify(le, mi, pos, typ);
    else
      Modify(mi + 1, ri, pos, typ);
    key[idx(le, ri)] = max(key[idx(le, mi)], key[idx(mi + 1, ri)]);
  }
} Se;
bool cmpval(const int& a, const int& b) { return val[a] < val[b]; }
bool cmpnum(const int& a, const int& b) { return num[a] < num[b]; }
long long Solve() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d%d", &num[i], &val[i]);
  for (int i = 0; i <= n; i++) {
    nid[i] = vid[i] = i;
    ed[i] = 0;
    vot[i] = false;
  }
  sort(nid + 1, nid + 1 + n, cmpnum), sort(vid + 1, vid + 1 + n, cmpval);
  for (int i = 1; i <= n; i++) ed[num[i]]++, _nid[nid[i]] = i;
  for (int i = 1; i <= n; i++) ed[i] += ed[i - 1];
  Se.Build(1, n);
  int cur = 0;
  long long ret = 0;
  for (int i = 1, j = 1; i <= n; i++) {
    while (j <= n && num[nid[j]] <= cur) {
      if (!vot[nid[j]]) cur++;
      vot[nid[j]] = true;
      j++;
    }
    int it = vid[i];
    if (vot[it]) continue;
    pair<int, int> tmp = Se.Query(1, n, ed[cur]);
    if (~tmp.first) {
      Se.Modify(1, n, tmp.second, false);
      ret += val[it] - tmp.first;
    } else
      ret += val[it];
    Se.Modify(1, n, _nid[it], true);
    vot[it] = true, cur++;
  }
  return ret;
}
int main() {
  int cas;
  scanf("%d", &cas);
  while (cas--) printf("%lld\n", Solve());
  return 0;
}
