// Double type cost import java.util.*; public class Gotoh1f_lin_space { public static double C[][]; // Min cost (overall) public static double D[][]; // Min cost that ends in delete x_i public static double I[][]; // Min cost that ends in insert y_j public static double g = 2; // Gap opening cost public static double h = .5; // Gap continuation cost public static double w( char a, char b ) { if ( a == b ) return 0; else return 1; } public static double solveMinAlignCost(String x, String y) { int i, j; int m, n; m = x.length(); n = y.length(); C[1][0] = 0; for (j = 1; j <= n ; j++) { C[1][j] = g + j*h; // C(0,j) = gap(j) = g + j*h D[1][j] = C[1][j] + g; // D(0,j) = C(0,j) + g (def) } for (i = 1; i <= m; i++) { /* ============================================== Recylce row 1 ============================================== */ for ( j = 0; j <= n; j++ ) { C[0][j] = C[1][j]; D[0][j] = D[1][j]; I[0][j] = I[1][j]; } C[1][0] = g +i*h; // C(i,0) = gap(i) = g + i*h I[1][0] = C[1][0] + g; // I(i,0) = C(i,0) + g (def) for (j = 1; j <= n; j++) { D[1][j] = min2 ( D[0][j]+h , C[0][j]+g+h ); I[1][j] = min2 ( I[1][j-1]+h , C[1][j-1]+g+h ); C[1][j] = min3 ( D[1][j], I[1][j], C[0][j-1] + w( x.charAt(i-1), y.charAt(j-1) ) ); } } return C[1][n]; } public static double min2( double x, double y ) { return ( x < y ? x : y ); } public static double min3( double x, double y, double z ) { double m = ( x < y ? x : y ); return ( m < z ? m : z ); } public static void main(String[] args) { Scanner in = new Scanner(System.in); String x; String y; int i, j; double minCost; System.out.print("x = "); x = in.next(); System.out.print("y = "); y = in.next(); /* x = "AAAA"; y = "AAA"; */ C = new double[2][y.length()+1]; // Linear space ! D = new double[2][y.length()+1]; I = new double[2][y.length()+1]; minCost = solveMinAlignCost(x, y); System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("Min. Align. Cost = " + minCost ); System.out.println(); System.out.println(); } }