the longest common sub-sequence problem (Lcs,longerst Common subsequence).
The common sub-sequences of s1s2......si+1 and t1t2......tj+1 may be:
① when si+1=tj+1, append one at the end of the common subsequence of s1s2......si+1 and t1t2......tj+1.
Common sub-sequences of ②s1s2......si+1 and T1T2......TJ
Common sub-sequences of ③s1s2......si and t1t2......tj+1
So easy to get recursion relationship dp[i+1][j+1]= max{dp[i][j]+1, dp[i][j+1], dp[i+1][j])} (when si+1=tj+1)
max{dp[i][j+1], dp[i+1][j])} Other
The last obtained dp[n][m] is the length of the LCS.
At the same time think a little bit, you can find when si+1=tj+1, dp[i+1][j+1] as long as equal to dp[i][j]+1 on it.
Tips
How to think, first because si+1=tj+1, obviously Si and tj+1,si+1 and TJ are not equal. Then dp[i][j+1] and dp[i+1][j] are actually equal to dp[i][j].
① to note is that the S1 of the first letter in the array is s1[i-1] instead of s[i], s2 the same. So the following judgment is s1[i-1]==s2[j-1] what it wants to say is whether the S1 letter is equal to the S2 's J-letter, so it's consistent with the recursion above.
1 if ( s1[i-1] = = s2[j-1])2 dp[i][j] = dp[i-1][j-1]+ 1 ; 3 Else 4 DP[I][J] = max (dp[i-1][j], dp[i][j-1]);
Actually, I thought about it. I think this array starts with 0 and starts with 1 and is very fastidious.
The AC code is as follows:
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 using namespacestd;6 intdp[ the][ the];7 Chars1[ the],s2[ the];8 intMain ()9 {Ten One while(~SCANF ("%s%s",&s1,&S2)) A { - intlen1=strlen (S1); - intLen2=strlen (S2); the for(intI=0; I <= len1; i++) -dp[i][0]=0; - for(intj=0; J <= Len2; J + +) -dp[0][j]=0; + - for(intI=1; I <= len1; i++) + for(intj=1; J <= Len2; J + +) A { at if(s1[i-1] = = s2[j-1] ) -DP[I][J] = dp[i-1][j-1]+1; - Else -DP[I][J] = max (dp[i-1][J], dp[i][j-1] ); - } -printf"%d\n", Dp[len1][len2]); in } - return 0; to}
HDU 1159 Common subsequence (DP longest common sub-sequence problem LCS)