POJ 1458/HDU 1159 最长公共子序列 (动态规划)

题目链接:poj && hdu

求最长公共子序列的方法:http://blog.csdn.net/qq_21120027/article/details/47732257

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int M = 1010;
char str1[M], str2[M];
int dp[M][M];
int main()
{
#ifndef ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
#endif
    int i, j, k, len1, len2;
    while(~scanf("%s%s", str1+1, str2+1))
    {
        len1 = strlen(str1+1);
        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]);
                }
            }
        }
        cout << dp[len1][len2] << endl;
    }
    return 0;
}

你可能感兴趣的:(动态规划,poj)