HDU 1159 Common Subsequence (dp LCS)
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
SourceSoutheastern Europe 2003
Longest Common subsequence
# Include
# Include
# Include
Using namespace std; int max (int a, int B) {return a> B? A: B;} char a [1001], B [1001]; int dp [1000] [1000]; int main () {while (scanf ("% s", a, B )! = EOF) {int lena = strlen (a); int lenb = strlen (B); int I; for (I = 0; I <= lena; I ++) dp [I] [0] = 0; for (I = 0; I <= lenb; I ++) dp [0] [I] = 0; for (I = 1; I <= lena; I ++) for (int j = 1; j <= lenb; j ++) if (a [I-1] = B [J-1]) dp [I] [j] = dp [I-1] [J-1] + 1; else dp [I] [j] = max (dp [I] [J-1], dp [I-1] [j]); // This position is the left and top of the rectangle printf ("% d \ n", dp [lena] [lenb]);} return 0 ;} // The following example is for reference, easy to understand/* p r o g r a m n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 n 0 0 0 1 1 1 1 1 2 t 0 0 0 1 1 1 1 1 2e 0 0 0 0 1 1 1 1 1 1 2 s 0 0 0 1 1 1 1 1 2 t 0 0 0 1 1 1 1 2 */