program j01; const mo=9875321; var s:string; bo:array[0..9875321]of boolean; v1,v2:array[0..9875321]of longint; a:array[0..100]of longint; bin:array[0..10]of longint; fu:array[0..100]of boolean; time,n,v,i,ans,tmp,j:longint; ch:char; begin readln(time); bin[1]:=1; for i:=2 to 10 do bin[i]:=(bin[i-1]*27) mod mo; while time>0 do begin dec(time); readln(n); fillchar(fu,sizeof(fu),0); for i:=1 to n do begin read(ch); a[i]:=0;j:=0; while ch<>' ' do begin tmp:=ord(ch)-ord('a')+1; inc(j);a[i]:=(a[i]+(bin[j]*tmp)mod mo)mod mo; read(ch); end; readln(v); if bo[a[i]]=false then begin v1[a[i]]:=v;bo[a[i]]:=true; fu[i]:=true; end else begin if v>=v1[a[i]] then begin v2[a[i]]:=v1[a[i]]; v1[a[i]]:=v; end else begin if v>v2[a[i]] then v2[a[i]]:=v; end; end; end; ans:=0; for i:=1 to n do if fu[i] then ans:=ans+v1[a[i]]+v2[a[i]]; for i:=1 to n do begin bo[a[i]]:=false; v1[a[i]]:=0;v2[a[i]]:=0; end; writeln(ans); end; end.