from heapq import*
s=sorted
def f(x):
 s,n,*h=0,len(x)
 while n:
  while x and x[-1][0]>=n:k,l,r=x.pop();heappush(h,(r-l,l,r))
  if h:s+=heappop(h)[1]
  n-=1
 return s+sum(r for*_,r in x+h)
z=open(0).read().split()
i=1
while i<len(z):
 n,x,*y=int(z[i]),[];i+=1
 for k,l,r in zip(*[map(int,z[i:i+n*3])]*3):
  if l>r:x+=(k,l,r),
  else:y+=(n-k,r,l),
 print(f(s(x))+f(s(y)));i+=n*3