import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')

import heapq

t = int(input())
for _ in range(t):
	n = int(input())
	arr = []
	for i in range(n):
		m,p = map(int,input().split(" "))
		arr.append((-m,p,i))
	arr.sort()
	cnt = 1
	s = 0
	ans = 0
	pq = []
	heapq.heappush(pq,(arr[0][1],-arr[0][0],arr[0][2]))
	for i in range(1,n):
		if arr[i-1][0] == arr[i][0]:
			cnt += 1
		else:
			m = -arr[i-1][0]-s-(n-i)
			for j in range(m):
				a,b,c = heapq.heappop(pq)
				ans += a
			if m>0:
				s += m
			cnt = 1
		heapq.heappush(pq,(arr[i][1],-arr[i][0],arr[i][2]))

	m =  max(-arr[n-1][0]-s,0)
	# print "m=", m
	cnt = 0
	for i in range(m):
		a,b,c = heapq.heappop(pq)
			
		ans += a
			
	print ans









