Maximum Common Subsequence of HDU 1159
Problem DescriptionA subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = Another sequence Z = Is a subsequence of X if there exists a strictly increasing sequence Of indices of X such that for all j = 1, 2 ,..., k, xij = zj. for example, Z = is a subsequence of X = 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 Input
abcfbc abfcabprogramming contest abcd mnp
Sample Output
420
Source
Southeastern Europe 2003
This question is to find the maximum length of the common subsequence.
I don't know how to explain it.
I had to make a sketch.
# Include
# Include
# Define max (a, B) a> B? A: bchar s [520]; char s1 [520]; int lcs [520] [520]; int LCS (int l, int l1) {int I, j; // convert the two columns into rows I and columns j. The lsc array represents the length of the maximum common subsequence at each position. For (I = 1; I <= l; I ++) for (j = 1; j <= l1; j ++) // compare s [I-1] with each element of s1 respectively {if (s [I-1] = s1 [J-1]) // returns equal. Lcs [I] [j] = lcs [I-1] [J-1] + 1; // The case of else lcs [I] [j] = max (lcs [I-1] [j], lcs [I] [J-1]) in the diagram; // If an inequality exists, the maximum value of the top and left of the image is used. Use this to accumulate} return lcs [l] [l1]; // the final State must be the maximum length. The length in the figure is 2, the maximum common subsequence can be ca or AB .} Int main () {while (scanf ("% s", s, s1 )! = EOF) {int l = strlen (s); int l1 = strlen (s1); memset (lcs, 0, sizeof (lcs )); printf ("% d \ n", LCS (l, l1);} return 0 ;}