A very simple DP
If DP[I,J] represents the similarity between the two segments from 0 to I and from 0 to J,
Then you know that each dp[i,j] is transformed by three states.
The first kind of dna1[i]==dna2[j]
DP[I-1,J-1] + 1 length plus 1
The second, or else from the bottom two states.
DP[I][J-1] and dp[i-1][j]//note because it's sequential traversal, both of which have been computed
Take the two to the maximum.
#include <iostream>#include<cstring>#include<algorithm>using namespacestd;//Longest common sub-sequence length LCS dpChardna1[ ++Ten];Chardna2[ ++Ten];intlen1, Len2;intdp[ ++Ten][ ++Ten];//represents the similarity of dna1 from 1th to I and dna2 from first position to Jvoidinit () {cin>>Dna1; CIN>>Dna2; Len1=strlen (DNA1); Len2=strlen (DNA2);}intbuild () {memset (DP,0,sizeof(DP)); for(inti =1; I <= len1; ++i) { for(intj=1; J <= Len2; ++j) { BOOLOK = (dna1[i-1]==dna2[j-1]); DP[I][J]=Max (Dp[i-1][j-1] +OK, max (Dp[i-1][j], dp[i][j-1] ) ); } } returndp[len1][len2];}intMainintargcChar Const*argv[]) {init (); cout<<build () <<Endl; return 0;}
"Algorithm learning note" 72.LCS Max-father-in-law sub-sequence dynamic programming SJTU OJ 1065 Small M biological experiment 1