/*这道题是很明显的dp题,状态方程有点不大好想,也许是我刚刚接触dp的缘故吧。dp[i][j]表示字符串s1取前i个字符s2取前j个字符时最大公共子序列的大小,这样的如果s1[i]==s2[j],dp[i][j]=d[i-1][j-1]+1;
如果s1[1]!=s2[j],dp[i][j]=max{dp[i-1][j],dp[i][j-1]};*/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include"iostream" #include"stdio.h" #include"algorithm" #include"string.h" #include"ctype.h" #include"cmath" #include"queue" #define mx 1005 #define inf 32767 #define max(a,b) a>b?a:b using namespace std; int dp[mx][mx]; char s1[mx],s2[mx]; int main() { while(scanf("%s%s",s1+1,s2+1)!=EOF) { int len1=strlen(s1+1); int len2=strlen(s2+1); int i,j; memset(dp,0,sizeof(dp)); for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(s1[i]==s2[j]) { dp[i][j]=dp[i-1][j-1]+1; } else dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } cout<<dp[len1][len2]<<endl; } return 0; }