Longest Common subsequence (LCS)

Source: Internet
Author: User

Simple DP.

F [I] [J] indicates the length of the first I in sequence A, and the first B in sequence B.

DP equation:

If (A [I-1] = B [J-1]) f [I] [J] = f [I-1] [J-1] + 1;
Else f [I] [J] = max (F [I-1] [J], F [I] [J-1]);

(My subscripts a start from 0, and f start from 1)

It is easy to understand, that is, if the current pair is the same, it is added. If the difference is different, it is maintained before.

Example: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1159

Code:

 1 #include<cstdio> 2 #include<cmath> 3 #include<iostream> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<map> 8 #include<set> 9 using namespace std;10 #define ll __int6411 #define usint unsigned int12 #define mz(array) memset(array, 0, sizeof(array))13 #define minf(array) memset(array, inf, sizeof(array))14 #define REP(i,n) for(int i=0;i<(n);i++)15 #define FOR(i,x,n) for(int i=(x);i<=(n);i++)16 #define RE  freopen("1.in","r",stdin)17 #define WE  freopen("1.out","w",stdout)18 19 const int maxn=1111;20 char a[1111],b[1111];21 int f[1111][1111];22 int main() {23     int la,lb,i,j,k;24     while(scanf("%s %s",a,b)!=EOF) {25         la=strlen(a);26         lb=strlen(b);27         mz(f);28         for(i=1; i<=la; i++)29             for(j=1; j<=lb; j++)30                 if(a[i-1]==b[j-1]) f[i][j]=f[i-1][j-1]+1;31                 else f[i][j]=max(f[i-1][j],f[i][j-1]);32         printf("%d\n",f[la][lb]);33     }34     return 0;35 }
View code

 

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.