#include <bits/stdc++.h>
using namespace std;
const int MOD7 = 1000000000 + 7;
const int MOD9 = 1000000000 + 9;
int main() {
  int t = ({
    int x;
    scanf("%d", &x);
    x;
  });
  while (t--) {
    int n = ({
      int x;
      scanf("%d", &x);
      x;
    });
    map<int, vector<int> > m;
    for (int i = (0); i < (n); i += (1)) {
      int mi = ({
        int x;
        scanf("%d", &x);
        x;
      }),
          pi = ({
            int x;
            scanf("%d", &x);
            x;
          });
      m[mi].push_back(pi);
    }
    vector<int> v;
    for (auto e : m) {
      v.push_back(e.first);
    }
    int allOther = n, bought = 0;
    long long cost = 0;
    multiset<int> notBought;
    for (int i = (((int)v.size()) - 1); i >= (0); i--) {
      int mi = v[i];
      allOther -= ((int)m[mi].size());
      if (bought + allOther >= mi) {
        for (auto pi : m[mi]) {
          notBought.insert(pi);
        }
      } else {
        int need = mi - bought - allOther;
        for (auto pi : m[mi]) {
          notBought.insert(pi);
        }
        for (int j = (0); j < (need); j += (1)) {
          cost += *notBought.begin();
          notBought.erase(notBought.begin());
          bought++;
        }
      }
    }
    cout << cost << "\n";
  }
}
