//IOI 2021
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define ff first
#define ss second

mt19937 parsa(chrono::steady_clock::now().time_since_epoch().count());

typedef long long ll;
typedef pair<ll, ll> pll;

const ll inf = 1e16;

int t;

int main() {
	ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> t;
	while (t--) {
		int n;
		cin >> n;
		pll val[n + 17] = {};
		for (int i = 1; i <= n; i++)
			cin >> val[i].ff >> val[i].ss;
		ll ans = inf;
		for (int i = 1; i <= 1000; i++) {
			shuffle(val + 1, val + n + 1, parsa);
			if (i == 1)
				sort(val + 1, val + n + 1);
			ll res = 0;
			for (int i = 1; i <= n; i++) {
				if (val[i].ff <= i - 1)
					continue;
				res += val[i].ss;
			}
			ans = min(ans, res);
		}
		cout << ans << '\n';
	}
	return 0;
}
