t = int(input())
for i in range(t):
	n = int(input())
	l = []
	for i in range(n):
		m,p = input().split()
		m = int(m)
		p = int(p)
		l.append((m,p))
	l.sort(key = lambda x: x[0])
	c = 0
	v = 0
	for i in range(n):
		if(l[i][0]<=c):
			c+=1
		else:
			v+=l[i][0]-c
			c+=l[i][0]-c+1
	l.sort(key = lambda x: x[1])
	ans = 0
	for i in range(n):
		if(v == 0):
			break
		if(l[i][0] != 1):
			ans+=l[i][1]
			v-=1
	print(ans)