The longest common subsequence problem and the knapsack problem are classic topics of the DP (Dynamic Planning) algorithm. It is worth in-depth mining to understand the DP algorithm IDEA.The problem is as follows:
Maximum public subsequence time limit: 3000 MS | memory limit: 65535 KB difficulty: 3
-
-
Description
-
We will not turn around. For example, what you need to do is to write a program to obtain the longest common subsequence.
Tip: The Longest Common subsequence is also called the longest common substring (not consecutive). It is abbreviated as LCS (longest common subsequence ). It is defined as a sequence S. If it is a subsequence of two or more known sequences, and it is the longest of all sequences that meet this condition, S is the longest common subsequence of known sequences.
-
-
Input
-
-
The first line returns an integer N (0 <n <100) indicating the number of data groups to be tested.
Next, two rows of data in each group are the strings to be tested. Each string cannot exceed 1000 characters in length.
-
-
Output
-
-
Each group of test data outputs an integer, indicating the maximum length of the common subsequence. Each result group occupies one row.
-
-
Sample Input
-
-
2asdfadfsd123abcabc123abc
-
-
Sample output
-
-
36
Algorithm Analysis: Based on the meaning of the question, we need to find the same longest sequence of any two strings (the same one-to-one sequence is not required), then the first group of data in the question is, we can start with A or D or F, which has a variety of different situations, so dynamic planning is required to solve the problem, for LCs may be included in S and ti-1, it may also exist in Si-1 and Ti, or between Si and Ti, which makes us realize that the last point is the starting point of the problem, there are two situations:
If S1 [I] = S2 [J], DP [I] [J] = DP [I-1] [J-1] + 1 otherwise, DP [I] [J] = max (DP [I-1] [J], DP [I] [J-1])
The DP equation is
The one-dimensional DP code is as follows:
# Include <iostream> # include <cstring> using namespace STD; char S1 [1001], S2 [1001]; int DP [1001], t, x, y; int main () {CIN> T; while (t --) {CIN> S1> S2; memset (DP, 0, sizeof (DP )); int lens1 = strlen (S1), lens2 = strlen (S2); For (INT I = 0; I <lens1; I ++) {x = 0; for (Int J = 0; j <lens2; j ++) {Y = DP [J]; If (S1 [I] = S2 [J]) DP [J] = x + 1; else if (DP [J-1]> DP [J]) DP [J] = DP [J-1]; X = y ;}} cout <DP [lenS2-1] <"\ n";} return 0 ;}
The two-dimensional DP code is as follows:
# Include <stdio. h> # include <string. h> # define Max 1000int DP [Max + 1] [Max + 1]; char s [Max], t [Max]; int max (int A, int B) {return A> B? A: B;} int main () {int N, I, j, n, m; scanf ("% d", & N); While (n --) {scanf ("% S % s", S, T); int x = strlen (s), Y = strlen (t); for (I = 0; I <X; I ++) {for (j = 0; j <Y; j ++) if (s [I] = T [J]) DP [I + 1] [J + 1] = DP [I] [J] + 1; elsedp [I + 1] [J + 1] = max (DP [I + 1] [J], DP [I] [J + 1]);} printf ("% d \ n", DP [I] [J]);} return 0 ;}