这题没问题,题目提交的时候略坑,开200*200的数组结果WA,开了1000*1000的数组然后AC了,好奇怪的感觉,不知道为什么
设序列X=【x1,x2,x3….xm】,Y =【y1,y2,y3,…..yn】的最长公共子序列为Z=【z1,z2,z3……zk】
则
(1)若Xm = Yn则Zk = Xm = Yn,且Zk-1是Xm-1和Yn-1的最长公共子序列;
(2)若Xm != Yn,且Zk != Xm,则Z是Xm-1和Y的最长公共子序列;
(3) 若 Xm != Yn,且Zk != Yn,则Z是X和Yn-1的最长公共子序列;
0 i=0,j=0
C[i][j] = C[i-1][j-1] +1 i,j>0;Xi == Yj
max{C[i-1][j],C[i][j-1]} i,j >0,Xi!=Yj 转移方程
#include <cstdio> #include <iostream> #include <cstring> using namespace std; char X[1010],Y[1010]; int C[1010][1010]; void LCSLength(int m,int n,char x[],char y[]) { int i,j; for(i = 1; i <= m; i++) { C[i][0] = 0; } for(i = 1; i <= n; i++) { C[0][i] = 0; } for(i = 1; i <= m; i++) { for(j = 1; j <= n; j++) { if(x[i-1] == y[j-1]) { C[i][j] = C[i-1][j-1] + 1; } else { C[i][j] = max(C[i-1][j],C[i][j-1]); } } } } int main() { while(scanf("%s %s",X,Y)!=EOF ) { int m = (int)strlen(X); int n = (int)strlen(Y); LCSLength(m,n,X,Y); cout<<C[m][n]<<endl; } return 0; }