Problem descriptiona subsequence of a given sequence is the given sequence with some elements (possible none) left out. given a sequence X = <x1, x2 ,..., XM> another sequence z = <Z1, Z2 ,..., ZK> is a subsequence of X if there exists a strictly increasing sequence <I1, I2 ,..., ik> of indices of X such that for all j = 1, 2 ,..., k, Xij = ZJ. for example, Z = <A, B, F, C> is a subsequence of X = <A, B, C, F, B, c> with index sequence <1, 2, 4, 6>. given two sequences x and y the problem is to find the length of the maximum-length common subsequence of X and Y.
The program input is from a text file. each data set in the file contains two strings representing the given sequences. the sequences are separated by any number of white spaces. the input data are correct. for each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample inputabcfbc abfcabprogramming contest ABCD MNP
Sample output420 key point: to master the problem conversion, the key point is to understand, assuming the sequence X = {x1, x2... xm} and Y = {y1, Y2 ,... the longest common subsequence of yn} is Z = {Z1, Z2... ZK) (1) If XM = YN then zk = XM = YN and the Zk-1 is the longest common subsequence of the Xm-1 and the Yn-1 (2) if XM is not equal to YN, and ZK is not equal to XM, z is the longest common subsequence of Xm-1 and Y (3) if XM is not equal to YN, if ZK is not equal to YN, z is the longest common subsequence of x and Yn-1.
# Include <stdio. h>
# Include <string. h>
Int C [500] [500], Lena, lenb;
Int max (int A, int B ){
If (A> = B)
Return;
Else
Return B;
}
Int main (){
Char A [1, 500], B [2, 500];
While (scanf ("% S % s", a, B) = 2 ){
Lena = strlen ();
Lenb = strlen (B );
For (INT I = 0; I <Lena; I ++)
C [I] [0] = 0;
For (Int J = 0; j <lenb; j ++)
C [0] [J] = 0;
For (INT I = 1; I <= Lena; I ++)
For (Int J = 1; j <= lenb; j ++ ){
If (A [I-1] = B [J-1]) // here you need to note that you cannot forget the comparison of character a [0], B [0, therefore, Lena must be calculated in the calculation process.
C [I] [J] = C [I-1] [J-1] + 1;
Else
C [I] [J] = max (C [I-1] [J], C [I] [J-1]);
}
Printf ("% d \ n", C [Lena] [lenb]);
}
Return 0;
}
Maximum common subsequence