HDU1159最长公共字串

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

辅助空间变化示意图

 

a
b
c
f
b
c
a
1
1
1
1
1
1
b
1
2
2
2
2
2
f
1
2
2
3
3
3
c
1
2
3
3
3
4
a
1
2
3
3
3
4
b
1
2
3
3
4
4

由于f(i,j)只和f(i-1,j-1), f(i-1,j)和f(i,j-1)有关, 而在计算f(i,j)时, 只要选择一个合适的顺序, 就可以保证这三项都已经计算出来了, 这样就可以计算出f(i,j). 这样一直推到f(len(a),len(b))就得到所要求的解了.
if(a[i]==b[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);p
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1000;
char a[maxn],b[maxn];
int dp[maxn][maxn];
int main()
{
    int n,m;
    while(cin>>a>>b)
    {
        n=strlen(a);
        m=strlen(b);
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(a[i-1]==b[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        }
        cout<<dp[n][m]<<endl;
    }
    return 0;
}



你可能感兴趣的:(HDU1159最长公共字串)