题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159
解题报告:原来看到这个类形的题,感觉无从下手,那时候还不明白动态规划的思想,最近在学习动态规划,感觉很神奇的东西,只要有最优子结构的问题,一般都可以转换为动态规划,使时间复杂度降为多项式的问题
这道题目刚开始学动态规划,时间复杂度为你n^2,空间复杂度也是n^2,今后慢慢学习优化,
co[i][j]用来存放str1,str2,的公共部分最长有多长
code:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int co[1005][1005],len1,len2;
char str1[1005],str2[1005];
int main()
{
while(scanf("%s%s",str1,str2)!=EOF)
{
memset(co,0,sizeof(co));
len1=strlen(str1);
len2=strlen(str2);
for(int i=1;i<=len1;i++)
for(int j=1;j<=len2;j++)
{
if(str1[i-1]==str2[j-1])
co[i][j]=co[i-1][j-1]+1;
else
co[i][j]=max(co[i-1][j],co[i][j-1]);
}
printf("%d\n",co[len1][len2]);
}
return 0;
}