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