Main topic: Longest common sub-sequence
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 =,..., 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 sequences X and y the problem is to find the length of the Maximum-length common subsequence of x and Y. <br& Gt The program input was from a text file. Each data set in the file contains the strings representing the given sequences. The sequences is separated by any number of white spaces. The input data is correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from th E beginning of a separate line. <br>
Sample INPUTABCFBC abfcabprogramming contest ABCD MNP
Sample Output420 Problem Solving ideas: The two serialized into a matrix, followed by matching, f[i][j]=f[i-1][j-1]+1; (A[i]==b[j])
F[i][j]=max (F[i-1][j],f[i][j-1]) (A[i]!=b[j]);
n since f (i,j) is related only to F (i-1,j-1), F (i-1,j) and F (i,j-1), and in the calculation of F (i,j), it is possible to ensure that the three items are calculated by selecting an appropriate order, so that f (i,j) can be calculated. This is pushed to F (Len (a), Len (b)) to get the required solution. Code:
#include <iostream>#include<string.h>#include<algorithm>using namespacestd; intdp[1005][1005]; intMain () {intn,i,j; strings1,s2; Chararr[1005]; while(~SCANF ("%s", arr)) {S1=arr; scanf ("%s", arr); S2=arr; Memset (DP,0,sizeof(DP)); for(i=0; I<s1.length (); i++) { for(j=0; J<s2.length (); j + +) { if(s1[i]==S2[j]) {Dp[i+1][j+1]=dp[i][j]+1; } Else{dp[i+1][j+1]=max (dp[i][j+1],dp[i+1][j]); } }} cout<<dp[s1.length ()][s2.length ()]<<Endl; } }
Dynamic Planning 1002