POJ 1458 Common subsequence (Dp+lcs, longest common sub-sequence)

Source: Internet
Author: User

Test instructions: Given two strings, lets you find out the length of the longest common subsequence (LCS) between them.

Analysis: is obviously a DP, is the LCS, no change at all. Set two sequences, respectively, A1,A2, ... and B1,b2..,d (i, j) represent the length of two string LCS.

When a[i] = B[j], this length is the last length plus 1, namely: D (i, j) = d (i-1, j-1) + 1;

When a[i]! = B[j], that is the longest length of the front (because even if the latter is not true, it will not affect the front), namely: D (i, j) = Max{d (I-1, J), D (I, j-1)}.

The time complexity is MN, where m,n is the length of two sequences respectively.

The code is as follows:

#include <iostream>#include<cstring>#include<vector>#include<algorithm>#include<cstdio>using namespacestd;Const intMAXN = ++Ten;CharS1[MAXN], S2[MAXN];intD[MAXN][MAXN];intMain () { while(~SCANF ("%s", s1+1) {scanf ("%s", s2+1); intLen1 = strlen (s1+1); intLen2 = strlen (s2+1); memset (d,0,sizeof(d));  for(inti =1; I <= len1; ++i) for(intj =1; J <= Len2; ++j)if(S1[i] = = S2[j]) d[i][j] = d[i-1][j-1] +1; ElseD[I][J] = max (d[i-1][J], d[i][j-1]); printf ("%d\n", D[len1][len2]); }    return 0;}

POJ 1458 Common subsequence (Dp+lcs, longest common sub-sequence)

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.