#include<iostream>
#include<cstring>
#include <cstdio>
#include<string>
#include<queue>
#include<vector>
#include<map>
#include <set>
#include<ctime>
#include<cmath>
#include <cstdlib>
#include<algorithm>
using namespace std;
#define eps 1e-8
#define LL long long
const LL N=110000;
struct node {
LL c, d;
friend bool operator<(const node &a, const node &b) {
return a.d < b.d;
}
}w[N];
bool cmp(const node &a, const node &b) {
return a.c > b.c;
}
int main(){
LL T;
scanf("%lld", &T);
while (T--) {
LL n;
scanf("%lld", &n);
if (!n) {
printf("0\n");
continue;
}
for (LL i = 0; i < n; ++i)
scanf("%lld%lld", &w[i].d, &w[i].c);
sort(w, w + n, cmp);
LL cs = w[0].c, ans = 0;
node ft;
priority_queue<node> qu;
for (LL i = 0; cs; --cs) {
while (i < n && w[i].c >= cs) {
qu.push(w[i]);
++i;
}
if (!qu.empty()) {
ft = qu.top();
qu.pop();
ans += ft.d;
ft.d--;
if (ft.d) qu.push(ft);
}
}
printf("%lld\n", ans);
}
return 0;
}