t=eval(input())
damage=0
turn=1
for y in range(t):
    r=eval(input())
    o=[0,0,0]
    t=[0]
    th=[0]
    for i in range(r):
        str=input()
        p=str.split()
        a=int(p[0])
        if a==1:
            o.append(int(p[1]))
        elif a==2:
            t.append(int(p[1]))
        else:
            th.append(int(p[1]))
    mo1=max(o)
    mt=max(t)
    mth=max(th)
    o.remove(mo1)
    mo2=max(o)
    o.remove(mo2)
    mo3=max(o)
    a=mo1+mo2+mo3
    b=mt+mo1
    c=mth
    if c>=a and c>=b:
        if turn%10==0:
            damage+=(2*c)
            turn+=1
        else:
            damage+=c
            turn+=1
    elif b>=a:
        if turn%10==0 or ((turn+1)%10==0 and min(mo1,mt)!=0):
            damage+=2*max(mo1,mt)+min(mo1,mt)
        else:
            damage+=b
        if min(mo1,mt)==0:
            turn+=1
        else:
            turn+=2
    else:
        if turn%10==0 or ((turn+1)%10==0 and mo2!=0 and mo3==0) or ((turn+2)%10==0 and mo2!=0 and mo3!=0):
            damage+=max(mo1,mo2,mo3)+a
        else:
            damage+=a
        if mo2==0 and mo3==0:
            turn+=1
        elif mo3==0:
            turn+=2
        else:
            turn+=3
print(damage)
