// EditDistance.java import java.io.*; // Computes the edit distance between two strings of lowercase letters where // cost of insert(a) = cost of delete(a) = a for character a. // This is a variation of the standard edit distance problem solved // using dynamic programming. public class EditDistance { int lena, lenb; int[][] m; static BufferedReader in; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(in.readLine()); for (int i = 0; i < numCases; i++){ EditDistance ed = new EditDistance(); String[] inputs = readInput(); int res = ed.editDistance( inputs[0], inputs[1] ); System.out.println( res ); } } int editDistance( String a, String b ) { // initialization lena = a.length(); lenb = b.length(); m = new int[lena+1][lenb+1]; m[0][0] = 0; // rows of m correspond to chars in string a for (int i = 1; i <= lena; i++) m[i][0] = m[i-1][0] + cost( a, i ); // columns of m correspond to chars in string b for (int j = 1; j <= lenb; j++) m[0][j] = m[0][j-1] + cost( b, j ); // compute edit distance for (int i = 1; i <= lena; i++) for (int j = 1; j <= lenb; j++) { int costa = cost( a, i ); int costb = cost( b, j ); int diagonalCost = (a.charAt(i-1) == b.charAt(j-1)) ? 0 : (costa + costb); int min = m[i-1][j-1] + diagonalCost; if (m[i-1][j] + costa < min) min = m[i-1][j] + costa; if (m[i][j-1] + costb < min) min = m[i][j-1] + costb; m[i][j] = min; } return m[lena][lenb]; } int cost( String s, int i ) { return s.charAt(i-1) - 'a' + 1; } static String[] readInput() throws IOException { String[] res = new String[2]; String line = in.readLine(); int spaceIdx = line.indexOf(' '); res[0] = line.substring(0, spaceIdx); res[1] = line.substring(spaceIdx+1); return res; } }