import sys
import heapq
import math
input = sys.stdin.readline
sys.setrecursionlimit(100000)
from collections import *




def li():return [int(____) for ____ in input().rstrip('\n').split(' ')]
def val():return int(input().rstrip('\n'))
def st():return input().rstrip('\n')
def sttoli():return [int(i) for i in input().rstrip('\n')]



for _ in range(val()):
    n = val()
    l = []
    for i in range(n):l.append(li()+[i])
    heap = []
    for i in range(n):
        heapq.heappush(heap,[l[i][1],l[i][0],l[i][-1]])
    
    l.sort()
    # print(l)
    curr = {}
    currvot = 0
    tot = 0
    # print(sorted(heap))
    for i in range(n):
        if l[i][2] in curr:
            continue
        if l[i][0] > currvot:
            while len(heap) and currvot<l[i][0]:
                a,b,c = heapq.heappop(heap)
                # print("ELEMENT",a,b,c,currvot)
                if c == l[i][2]:


                    if len(heap):temp = heapq.heappop(heap)
                    else:break

                    # print("CHECK",temp,currvot)
                    if temp[1]>=currvot + 2 and currvot + 1 == l[i][0]:
                        tot += temp[0]
                        curr[temp[-1]] = 1
                        # print("CHECK@",temp,curr)
                        currvot += 1
                        
                    else:
                        heapq.heappush(heap,temp)
                    break
                elif c not in curr and currvot>=b:
                    curr[c] = 1
                    currvot += 1
                    break
                elif c not in curr:
                    currvot += 1
                    curr[c] = 1
                    tot += a
            if currvot>=l[i][0]:
                curr[l[i][2]] = 1
                break
            curr[l[i][2]] = 1
            tot += l[i][1]
            # print(curr)
        else:
            curr[l[i][2]] = 1

                
                



        currvot += 1
    print(tot)