{
TASK: LDIST
LANG: PASCAL
}

var i,j,r,h,y,d1,d2,p,q,t,K,L:word;
    x,z,PROB:char;
    D:array[1..37,1..37] of word;
    V:array[1..37] of word;
    A,B:array[1..1024] of char;
    c:array[0..1023,0..1023] of word; {FREE P}

function ret(cc:char):word;
begin
     case cc of
          '1':ret:=1;
          '2':ret:=2;
          '3':ret:=3;
          '4':ret:=4;
          '5':ret:=5;
          '6':ret:=6;
          '7':ret:=7;
          '8':ret:=8;
          '9':ret:=9;
          '0':ret:=10;
          'A':ret:=11;
          'B':ret:=12;
          'C':ret:=13;
          'D':ret:=14;
          'E':ret:=15;
          'F':ret:=16;
          'G':ret:=17;
          'H':ret:=18;
          'I':ret:=19;
          'J':ret:=20;
          'K':ret:=21;
          'L':ret:=22;
          'M':ret:=23;
          'N':ret:=24;
          'O':ret:=25;
          'P':ret:=26;
          'Q':ret:=27;
          'R':ret:=28;
          'S':ret:=29;
          'T':ret:=30;
          'U':ret:=31;
          'V':ret:=32;
          'W':ret:=33;
          'X':ret:=34;
          'Y':ret:=35;
          'Z':ret:=36;
          '_':ret:=37;
          else ret:=0;
     end;
end;

function min(x,y,z:word):word;
begin
     if x>y then x:=y;
     if x>z then x:=z;
     min:=x;
end;

begin
     for i:=1 to 37 do begin
         V[i]:=100;
         for j:=1 to 37 do D[i,j]:=100;
     end;

     readln(r);
     for i:=1 to r do begin
         read(x,y);
         V[ret(x)]:=y;
     end;
     readln(h);
     for i:=1 to h do begin
         readln(x,PROB,z,y);
         D[ret(x),ret(z)]:=y;
         D[ret(Z),ret(X)]:=y;
     end;
     read(x); i:=0;
     while ret(x)<>0 do begin
           inc(i);
           A[i]:=x;
           read(x);
     end;
     d1:=i;
     read(x); j:=0;
     while ret(x)=0 do read(x);
     while ret(x)<>0 do begin
           inc(j);
           B[j]:=x;
           read(x);
     end;
     d2:=j;

     C[0,0]:=0;
     for i:=1 to d1 do C[i,0]:=C[i-1,0]+V[ret(A[i])];
     for i:=1 to d2 do C[0,i]:=C[0,i-1]+V[ret(B[i])];
     for i:=1 to d1 do
         for j:=1 to d2 do C[i,j]:=0;

     for i:=1 to d1 do
         for j:=1 to d2 do begin
             p:=C[i-1,j]+V[ret(A[i])];
             q:=C[i,j-1]+V[ret(B[j])];
             if A[i]=B[j]
                then t:=c[i-1,j-1]
                else t:=c[i-1,j-1]+D[ret(A[i]),ret(B[j])];
             C[i,j]:=min(p,q,t);

         end;

    writeln(c[d1,d2]);
end.
