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