Uploaded
Hzyqazasdf
Start to brush dynamic planning of the problem; from the entry to practice hands, http://blog.csdn.net/v_july_v/article/details/6695482 (about the algorithm to explain) refer to the blog of the great god, I have read a little bit about this content. I can use this topic to practice it. Master the idea of dynamic planning!
The idea of dynamic planning is mainly a recursive formula, which is used to find the optimization problem and ensure that the current position is the best and the principle of division is adopted;
The idea of this question is that, starting from the last character, if the last character of the two strings is the same, it indicates that the last character, in the longest public sequence, is the first of the longest public sequence, it must be the longest common subsequence of two strings. the recursive formula is dp [I] [J] = DP [I-1] [J-1] + 1;
In other cases, if they are not equalDP [I] [J] = max (DP [I] [J-1], DP [I-1] [J]);
Code that has been watered for the first time;
# Include <cstdio> # include <cstring> # define max (A, B) A> B? A: busing namespace STD; const int maxn = 1001; int DP [maxn] [maxn]; // Save the maximum number of common subsequences in the current position. Char S1 [maxn], s2 [maxn]; int main () {int N; int len1, len2; scanf ("% d", & N); getchar (); While (n --) {memset (DP, 0, sizeof (DP); scanf ("% S % s", S1, S2); len1 = strlen (S1 ); len2 = strlen (S2); For (INT I = 1; I <= len1; I ++) for (Int J = 1; j <= len2; j ++) {If (S1 [I-1] = S2 [J-1]) // previously this place was written as S1 [I] = S2 [J] and Wa never knew why, sample can pass DP [I] [J] = DP [I-1] [J-1] + 1; else DP [I] [J] = max (DP [I] [J-1], DP [I-1] [J]);} printf ("% d \ n ", DP [len1] [len2]);} return 0 ;}
We can see that others can directly use a one-dimensional array for memory optimization. It is worth learning;
# Include <stdio. h> # include <string. h> char S1 [1001], S2 [1001]; int DP [1001], T, old, TMP; int main () {scanf ("% d ", & T); getchar (); While (t --) {gets (S1); gets (S2); memset (DP, 0, sizeof (DP )); int lens1 = strlen (S1), lens2 = strlen (S2); For (INT I = 0; I <lens1; I ++) {old = 0; // 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]) // Spatial Optimization is performed here, old stands for DP [I-1] [J-1] // DP [J-1] stands for DP [I] [J-1], DP [J] stands for DP [I-1] [J] For (Int J = 0; j <lens2; j ++) {TMP = DP [J]; if (S1 [I] = S2 [J]) DP [J] = old + 1; else if (DP [J-1]> DP [J]) DP [J] = DP [J-1]; old = TMP;} printf ("% d \ n", DP [lenS2-1]);} return 0 ;}