Question: uva10405-Longest Common subsequence (LIS, longest common sequence)
Find the longest common subsequence of two strings.
Solution: this type of problem is the first contact and I don't know how to do it. Baidu once found the recurrence formula: DP [I] [J ]: represents the longest common subsequence that can be obtained by comparing the first I character of the first string with the first J character of the second string. S [I] = s [J], DP [I] [J] = DP [I-1] [J-1] + 1; s [I ]! = S [J], DP [I] [J] = max (DP [I] [J-1], DP [I-1] [J]); Initialization: DP [I] [0] = DP [0] [J] = 0; (I> = 1 & I <= L1 [length of the first string], j> = 1 & J <= l2)
If they are equal, DP [I-1] [J-1] + 1 is used, because DP [I-1] [J ], the DP [I] [J-1] value must be less than or equalDP [I-1] [J-1] + 1, because here I-1 characters must have to spend one character to match with J, in this case, the optimal scenario is DP [I-2] [J-1] + 1.DP [I-1] [J-1]> = KDP [I-2] [J-1], becauseThe length of the two matched substrings is longer, so that the length of the same string is larger. Otherwise, it is easier to understand.
There may be a null string.
Code:
# Include <cstdio> # include <cstring> const int n = 1005; char S1 [N], S2 [N]; int L [N] [N]; int L1, l2; void Init () {memset (L, 0, sizeof (l); L1 = strlen (S1); L2 = strlen (S2 );} int max (const int A, const int B) {return A> B? A: B;} int main () {While (gets (S1 )! = NULL) {gets (S2); Init (); For (INT I = 1; I <= L1; I ++) for (Int J = 1; j <= L2; j ++) if (S1 [I-1] = S2 [J-1]) L [I] [J] = L [I-1] [J-1] + 1; elsel [I] [J] = max (L [I] [J-1], L [I-1] [J]); printf ("% d \ n ", L [L1] [L2]);} return 0 ;}