首页 > 代码库 > uva--10405Longest Common Subsequence+dp

uva--10405Longest Common Subsequence+dp

经典的最长公共子序列问题。

要注意的是题目中的输入会包含空格的情况,所以要用gets实现输入。


代码如下:


<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int dp[1100][1100];

int main()
{
    char str1[1100],str2[1100];
    int i,j;
    while(gets(str1+1))
    {
        gets(str2+1);
        int len1=strlen(str1+1);
        int len2=strlen(str2+1);
        memset(dp,0,sizeof(dp));
        for(i=1;i<=len1;i++)
            for(j=1;j<=len2;j++)
            {
                if(str1[i]==str2[j])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        int ans=0;
        for(i=1;i<=len1;i++)
            for(j=1;j<=len2;j++)
                ans=max(ans,dp[i][j]);
        printf("%d\n",ans);
    }
  return 0;
}</span>


uva--10405Longest Common Subsequence+dp