#include <bits/stdc++.h>
using namespace std;
struct peo {
  long long m, p;
} p[5005];
long long t, n, si, ans, minn, i, j, q, pl, has;
inline long long cmp(peo aaa, peo bbb) { return aaa.m < bbb.m; }
signed main() {
  cin >> t;
  while (t--) {
    cin >> n;
    for (i = 1; i <= n; ++i) {
      cin >> p[i].m >> p[i].p;
    }
    sort(p + 1, p + n + 1, cmp);
    has = si = ans = 0;
    for (i = 1; i <= n; ++i) {
      if (p[i].m <= has) {
        ++has;
      } else
        break;
    }
    for (i = has + 1; i <= n; ++i) {
      p[++si].m = p[i].m - has;
      p[si].p = p[i].p;
    }
    while (si) {
      minn = 999999999999;
      for (i = si; i; --i) {
        if (p[i].p < minn) {
          minn = p[i].p;
          pl = i;
        }
        if (p[i].m > i - 1) {
          ans += minn;
          break;
        }
      }
      for (j = pl + 1; j <= si; ++j) {
        p[j - 1].m = p[j].m;
        p[j - 1].p = p[j].p;
      }
      --si;
      has = 0;
      for (j = 1; j <= si; ++j) {
        p[j].m -= 1;
      }
      for (j = 1; j <= si; ++j) {
        if (p[j].m <= has) {
          ++has;
        } else
          break;
      }
      for (j = has + 1; j <= si; ++j) {
        p[j - has].m = p[j].m - has;
        p[j - has].p = p[j].p;
      }
      si -= has;
    }
    cout << ans << "\n";
  }
  return 0;
}
