#include <bits/stdc++.h>
using namespace std;
int num[211111];
vector<int> allv[211111];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, a, b;
    scanf("%d", &n);
    for (int i = 0; i < n + 1; i++) num[i] = 0, allv[i].clear();
    priority_queue<pair<int, int>, vector<pair<int, int> >,
                   greater<pair<int, int> > >
        allpq;
    priority_queue<int> pq;
    for (int i = 1; i < n + 1; i++)
      scanf("%d%d", &a, &b), num[a]++, allpq.emplace(b, a);
    int nownum = 0;
    long long res = 0;
    for (int i = 0; i < n + 1; i++) {
      if (num[i]) {
        int k = 0;
        while (nownum < i) {
          while (allpq.top().second < i) allpq.pop();
          pair<int, int> xx = allpq.top();
          res += xx.first, num[xx.second]--,
              allv[xx.second].push_back(xx.first);
          allpq.pop();
          if (!num[i]) break;
          nownum++, k++;
        }
        for (int i = 0; i < k; i++)
          if (!pq.empty()) res -= pq.top(), pq.pop();
        nownum += num[i];
      }
      for (int k : allv[i]) pq.push(k);
    }
    printf("%I64d\n", res);
  }
}
