// O(length^3 * letters^2) DP solution to 'Assembly line'. // Enrique Martin Martin import java.lang.*; import java.util.*; import java.io.*; import java.util.regex.Pattern; public class cheap{ static final int MAXL = 200; //Maximum chain length static final int MAXA = 'z'-'a' + 1; //Maximum number of letters: 'z'-'a' static final int INF = 1000000000; static char letter[] = new char[MAXA]; //Positions of letters static int multCost[][] = new int[MAXA][MAXA]; //Cost of the multiplication of 2 letters static int multRes[][] = new int[MAXA][MAXA]; //Result of the multiplication of 2 letters static int cost[][][] = new int[MAXL][MAXL][MAXA]; //Minimum cost of multiplying in a substring cost[i][j] obtaining a particular letter static String s; static private int getPosition( char c ) { for( int i = 0; i < MAXA; ++i ) if( letter[i] == c ) return i; return -1; //This will not happen because c is supposed to appear in letter[] } static private void minimumCost( String s, int len, int numLetters ) { int c1, c2, minc, actc; for( int i = 0; i < len; i++ ) for( int j = 0; j < len; j++ ) for( int k = 0; k < numLetters; k++ ) cost[i][j][k] = INF; /*Base case, substrings of length 1*/ for( int i = 0; i < len; ++i ) { int pos = getPosition( s.charAt(i) ); cost[i][i][pos] = 0; } /*Substrings of length > 1*/ for( int diag = 1; diag < len; diag++ ) { for( int i = 0; i+diag < len; i++ ) { /*Substring [i,i+diag]*/ for( int k = i; k < i+diag; k++ ) { for( int l1 = 0; l1 < numLetters; l1++ ) { for( int l2 = 0; l2 < numLetters; l2++ ) { if( cost[i][i+diag][ multRes[l1][l2] ] > (cost[i][k][l1] + cost[k+1][i+diag][l2] + multCost[l1][l2] ) ) cost[i][i+diag][ multRes[l1][l2] ] = cost[i][k][l1] + cost[k+1][i+diag][l2] + multCost[l1][l2]; } } } } } } public static void main(String[] args) { int k, costMul, n, m, len; char res; Scanner scanner = new Scanner(System.in); m = 0; for(;;) { k = scanner.nextInt(); if( k == 0 ) break; if( m > 0 ) System.out.println(); m++; Pattern patPar = Pattern.compile("([0-9]+)-[a-z]"); Pattern patChar = Pattern.compile("[a-z]"); Pattern patSpace = Pattern.compile("[ ]"); for( int i = 0; i < k; i++ ) { letter[i] = scanner.next( patChar ).charAt(0); } for( int i = 0; i < k; i++ ) { for( int j = 0; j < k; j++ ) { String par = scanner.next( patPar ); costMul = Integer.parseInt( par.substring(0, par.length()-2) ); res = par.charAt(par.length()-1); multRes[i][j] = getPosition(res); multCost[i][j] = costMul; } } n = scanner.nextInt(); scanner.nextLine(); for( int i = 0; i < n; i++ ) { s = scanner.nextLine(); len = s.length(); minimumCost( s, len, k ); int mincost = INF; for( int j = 0; j < k; j++ ) { if ( cost[0][len-1][j] < mincost ) mincost = cost[0][len-1][j]; } for( int j = 0; j < k; j++ ) { if ( cost[0][len-1][j] == mincost ) { System.out.print(mincost); System.out.print("-"); System.out.println(letter[j]); break; } } } } } }