迭代版:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int M=310;
typedef char ELEM;
ELEM X[M];
ELEM Y[M];
int c[M][M];
int LCS_LENGTH(int XLen,int YLen)
{//cout<<XLen<<" "<<YLen<<endl;
for(int i=1;i<=XLen;i++) c[i][0]=0;
for(int j=0;j<=YLen;j++) c[0][j]=0;
for(int i=1;i<=XLen;i++)
for(int j=1;j<=YLen;j++){//cout<<i<<" "<<X[i]<<" "<<j<<" "<<Y[j]<<endl;
if(X[i]==Y[j]){ c[i][j]=c[i-1][j-1]+1;}
else if(c[i-1][j]>=c[i][j-1]){ c[i][j]=c[i-1][j]; }
else{ c[i][j]=c[i][j-1]; }}
return c[XLen][YLen];
}
int main()
{
//freopen("memoized lcs.txt","r",stdin);
while(cin>>X+1>>Y+1){
cout<<LCS_LENGTH(strlen(X+1),strlen(Y+1))<<endl;
// for(int i=0;i<=strlen(X+1);i++){
// for(int j=0;j<=strlen(Y+1);j++) cout<<c[i][j]<<" ";
// cout<<endl;}
}
return 0;
}
带备忘递归版:
//要用负数(此处是-1)来表示未被计算的LCS长度,不能用0。因为LCS长度有可能为0。故遇到c[i][j]=0时,以为未被计算(会再次递归),其实很多时候已算,故TLE了
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int M=310;
typedef char ELEM;
ELEM X[M];
ELEM Y[M];
int c[M][M];
int MEMOIZED_LCS_LENGTH(int i,int j)
{
if(i==0||j==0) return c[i][j]=0;
if(c[i][j]>=0) return c[i][j];
if(X[i]==Y[j]) return c[i][j]=MEMOIZED_LCS_LENGTH(i-1,j-1)+1;
else return c[i][j]=max(MEMOIZED_LCS_LENGTH(i-1,j),MEMOIZED_LCS_LENGTH(i,j-1));
}
int main()
{
//freopen("lcs.txt","r",stdin);
while(scanf("%s%s",X+1,Y+1)==2){
int XLen=strlen(X+1),YLen=strlen(Y+1);
memset(c,-1,sizeof(c));
// c=new int*[XLen+5];
// for(int i=0;i<=XLen;i++) c[i]=new int[YLen+5]();
printf("%d\n",MEMOIZED_LCS_LENGTH(XLen,YLen));
// for(int i=0;i<=strlen(X+1);i++){
// for(int j=0;j<=strlen(Y+1);j++) cout<<c[i][j]<<" ";
// cout<<endl;}
// for(int i=0;i<=XLen;i++) delete[] c[i];
// delete[] c;
}
return 0;
}