The classic longest common subsequence problem.
The state transition equation is:
if (x[i] = = Y[j]) dp[i, j] = Dp[i-1, j-1] +1else dp[i, j] = Max (dp[i-1], J, Dp[i, J-1]);
With string x and string Y,dp[i, J] represents the longest common subsequence length of the first I-character of X and the first J-character of Y.
If x[i] = = Y[j], then this character and the previous LCS must be able to form a new LCS;
If x[i]! = Y[j], then examine dp[i-1][j] respectively, and Dp[i, J-1], select the larger of which is LCS.
Source Code:
//#pragma COMMENT (linker, "/stack:16777216")//For C + + Compiler#include <stdio.h>#include<iostream>#include<cstring>#include<cmath>#include<stack>#include<queue>#include<vector>#include<algorithm>#definell Long Long#defineMax (b) ((a) > (b))? (a): (b))#defineMin (b) ((a) < (a))? (a): (b))#defineAbs (x) (((x) > 0)? (x): (-(x)))using namespacestd;Const intINF =0x3f3f3f3f;Const intMAXN = -;intDP[MAXN][MAXN];intMain () {intI, J, T, K, N, M; intLen1, Len2; stringstr1, str2; while(Cin >> STR1 >>str2) {memset (DP,0,sizeof(DP)); Len1=str1.length (); Len2=str2.length (); for(i =1; I <= len1; ++i) { for(j =1; J <= Len2; ++j) { if(Str1[i-1] = = Str2[j-1]) {Dp[i][j]= Dp[i-1][j-1] +1; } Else{Dp[i][j]= Max (Dp[i-1][J], Dp[i][j-1]); } }} cout<< Dp[len1][len2] <<Endl; } return 0;}
POJ 1458 longest common sub-sequence LCS