hdu 2159

来源:互联网 发布:mac网页怎么添加收藏 编辑:程序博客网 时间:2024/06/06 01:21

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1159

题意很简单,即求两个字符串的最长公共子序列的长度

利用一个二维数组dp[i][j]储存,第一个字符串前I个字符与第二个字符串前j个字符的公共子串长度,一种回溯的思想。

状态转移方程:

if(str[i-1]!=str[j-1])

dp[i][j]=Max(dp[i-1][j],dp[i][j-1])(其中1<i<str1.length,1<j<str2,length)//如果字符串不相等的话,取第一个字符串前i-1和第二个字符串j-1个元素中公共子串长的那个

else

dp[i][j]=dp[i-1][j-1]+1;

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

代码:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <string>using namespace std;int maxn(int a,int b){    return a>b?a:b;}int dp[1005][1005];int main(){    string s1,s2;    while(cin>>s1>>s2)    {        memset(dp,0,sizeof(dp));        int len1=s1.size();        int len2=s2.size();        for(int i=1;i<=len1;i++)        {            for(int j=1;j<=len2;j++)            {                if(s1[i-1]==s2[j-1])                    dp[i][j]=dp[i-1][j-1]+1;                else                    dp[i][j]=maxn(dp[i-1][j],dp[i][j-1]);            }        }        printf("%d\n",dp[len1][len2]);    }    return 0;}