Test instructions: Given two strings, lets you find out the length of the longest common subsequence (LCS) between them.
Analysis: is obviously a DP, is the LCS, no change at all. Set two sequences, respectively, A1,A2, ... and B1,b2..,d (i, j) represent the length of two string LCS.
When a[i] = B[j], this length is the last length plus 1, namely: D (i, j) = d (i-1, j-1) + 1;
When a[i]! = B[j], that is the longest length of the front (because even if the latter is not true, it will not affect the front), namely: D (i, j) = Max{d (I-1, J), D (I, j-1)}.
The time complexity is MN, where m,n is the length of two sequences respectively.
The code is as follows:
#include <iostream>#include<cstring>#include<vector>#include<algorithm>#include<cstdio>using namespacestd;Const intMAXN = ++Ten;CharS1[MAXN], S2[MAXN];intD[MAXN][MAXN];intMain () { while(~SCANF ("%s", s1+1) {scanf ("%s", s2+1); intLen1 = strlen (s1+1); intLen2 = strlen (s2+1); memset (d,0,sizeof(d)); for(inti =1; I <= len1; ++i) for(intj =1; J <= Len2; ++j)if(S1[i] = = S2[j]) d[i][j] = d[i-1][j-1] +1; ElseD[I][J] = max (d[i-1][J], d[i][j-1]); printf ("%d\n", D[len1][len2]); } return 0;}
POJ 1458 Common subsequence (Dp+lcs, longest common sub-sequence)