

t = int(input())
for _ in range(t):
	n = int(input())
	arr = []
	for i in range(n):
		m,p = map(int,raw_input().split(" "))
		arr.append((-m,p,i))
	arr.sort()
	cnt = 1
	s = 0
	ans = 0
	visited= [0]*n
	for i in range(1,n):
		if arr[i-1][0] == arr[i][0]:
			cnt += 1
		else:
			m = -arr[i-1][0]-(n-cnt)-s
			for j in range(i-m,i):
				ans += arr[j][1]
				visited[arr[j][2]] = 1
			s += m
			cnt = 1
	arr.sort(key = lambda x:(x[1],x[0]))
	m =  -arr[n-1][0]-(n-cnt)-s
	cnt = 0
	for a,b,c in arr:
		if not visited[c]:
			cnt += 1
			ans += a
			if cnt == m:
				break
	print ans









