hdu 1159 common sequence (最长公共子序列 dp)

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

 

题意 : 给出两个字符串 求出最长公共子序列

 

思路: 

         

                if(str1[i]==str2[j]) { dp[i][j]=max(dp[i-1][j-1]+1,max(dp[i-1][j],dp[i][j-1])); } else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);

 

#include<cstdio>

#include<cstring>

#include<iostream>

#include<algorithm>

using namespace std;

char str1[1000],str2[1000];

int dp[1000][1000];

int main()

{

    int i,j,k;

    while(scanf("%s%s",str1+1,str2+1)!=EOF)

    {

        memset(dp,0,sizeof(dp));

        int len1=strlen(str1+1);

        int len2=strlen(str2+1);

        //cout<<len1<<" "<<len2<<endl;

        for(i=1;i<=len1;i++)

        {

            for(j=1;j<=len2;j++)

            {

                if(str1[i]==str2[j])

                {

                    dp[i][j]=max(dp[i-1][j-1]+1,max(dp[i-1][j],dp[i][j-1]));

                }

                else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);

            }

        }

        printf("%d\n",dp[len1][len2]);



    }

    return 0;

}

 

你可能感兴趣的:(sequence)