{
TASK: ldist
LANG: PASCAL
}
{$S-}
var v:Array[0..255]of Byte;
    d:Array[0..255,0..255]of Byte;
    s1:Array[1..1025]of Char;
    s2:Array[-2..2050]of Char;
    inds,inds2:Array[0..1025]of Longint;
    c:Char;
    p,q,i,j,min,l1,l2,tc:Longint;
    s:String;
    code:Integer;
Procedure Find(pps:Integer);
var i,j:Integer;
    found:Boolean;
Begin
 if pps<=l1 then
 Begin
  For i:=inds[pps-1]+1 to l1*2 do
  Begin
    inds[pps]:=i;
    find(pps+1);
  End;
 End
 Else
 Begin
   tc:=0;
  For i:=1 to l1 do
   tc:=tc+d[ord(s1[i]),ord(s2[inds[i]])];
  For i:=1 to l2 do
  Begin
    found:=false;
   for j:=1 to l1 do
    if inds[j]=i then
     Begin
       found:=True;
       Break;
     End;
   if not found then tc:=tc+v[ord(s2[i])];
  End;
   if tc<min then
   Begin
     min:=tc;
     inds2:=inds;
   End;
 End;
End;
Begin
 For i:=0 to 255 do
  v[i]:=100;
  v[0]:=0;
 For i:=0 to 255 do
  For j:=0 to 255 do
   d[i,j]:=100;
 For i:=0 to 255 do
  d[i,i]:=0;
  ReadLn(p);
 For i:=1 to p do
 Begin
   ReadLn(s);
   val(copy(s,pos(' ',s)+1,length(s)-pos(' ',s)),v[ord(s[1])],code);
 End;
  ReadLn(q);
 For i:=1 to q do
 Begin
   ReadLn(s);
   val(copy(s,5,length(s)-4),d[ord(s[1]),ord(s[3])],code);
   val(copy(s,5,length(s)-4),d[ord(s[3]),ord(s[1])],code);
 End;
 i:=0;
 Repeat
   read(c);
  if c=#13 then read(c)
  else
  Begin
    i:=i+1;
    s1[i]:=c;
    l1:=l1+1;
  End;
 Until c=#10;
 i:=0;
 Repeat
   read(c);
  if c=#13 then read(c)
  else
  Begin
    i:=i+1;
    s2[i]:=c;
    l2:=l2+1;
  End;
 Until c=#10;
  min:=maxlongint;
  inds[0]:=-1;
  find(1);
  WriteLn(min);
End.