Uva10405-Longest Common subsequence (LIS, longest common sequence)

Source: Internet
Author: User

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 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.