动态规划最长公共子序列

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100;
char a[N],b[N];
int dp[N][N];
int main()
{
    freopen("C:\\Users\\23535\\Desktop\\in.txt","r",stdin); //输入重定向,输入数据将从D盘根目录下的in.txt文件中读取 
    freopen("C:\\Users\\23535\\Desktop\\out.txt","w",stdout); //输出重定向,输出数据将保存在D盘根目录下的out.txt文件中 

    int n;
    gets(a+1);
    gets(b+1);
    int lena=strlen(a+1);
    int lenb=strlen(b+1);
    for(int i=0;i<=lena;i++)
    {
        dp[i][0]=0;
    }

    for(int j=0;j<=lenb;j++)
    {
        dp[0][j]=0;
    }
    for(int i=1;i<=lena;i++)
    {
        for(int j=1;j<=lenb;j++)
        {
            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]);
            }
        }
    }
    printf("%d\n",dp[lena][lenb]);
    fclose(stdin);//关闭重定向输入 
    fclose(stdout);//关闭重定向输出 

    return 0;
}

猜你喜欢

转载自blog.csdn.net/hhdmw/article/details/81258533