Longest Common subsequence template of LCS:
The state transition equation is
DP [I] [J] = DP [I-1] [J-1] + 1 If (in [I] = target [I])
= Max {DP [I-1] [J], DP [I] [J-1]} else;
Void lcslength (int m, int N, char * X, char * y, int ** C, int ** B)
{
Int I, J;
For (I = 1; I <= m; I ++) C [I] [0] = 0;
For (I = 1; I <= N; I ++) C [0] [I] = 0;
For (I = 1; I <= m; I ++)
For (j = 1; j <= N; j ++)
{
If (X [I] = Y [J]) {
C [I] [J] = C [I-1] [J-1] + 1; B [I] [J] = 1 ;} // B [I] [J] is used to construct the longest common subsequence.
Else if (C [I-1] [J]> = C [I] [J-1]) {
C [I] [J] = C [I-1] [J]; B [I] [J] = 2 ;}
Else {C [I] [J] = C [I] [J-1]; B [I] [J] = 3 ;}
}
}
Method 2:
Memset (DP, 0, sizeof (DP ));
Int len1 = in. Size ();
Int len2 = target. Size ();
For (I = 1; I <= len1; I ++) // The oldest sequence of LCS
For (j = 1; j <= len2; j ++)
{
If (in [I-1] = target [J-1])
DP [I] [J] = DP [I-1] [J-1] + 1;
Else
DP [I] [J] = max (DP [I-1] [J], DP [I] [J-1]);
}
The answer is DP [len1] [len2].
# Include <iostream>
# Include <string>
# Include <cstring>
Using namespace STD;
# Define x 250
Int DP [x] [X]; // I don't know how big
Int max (int A, int B)
{
Return A> B? A: B;
}
Int main ()
{
Freopen ("sum. In", "r", stdin );
Freopen ("sum. Out", "W", stdout );
String in, target;
Int I, J;
While (CIN> in> target)
{
Memset (DP, 0, sizeof (DP ));
Int len1 = in. Size ();
Int len2 = target. Size ();
For (I = 1; I <= len1; I ++) // The Longest Common subsequence template of LCS
For (j = 1; j <= len2; j ++)
{
If (in [I-1] = target [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;
}