1. 程式人生 > >POJ 1458/HDU 1159 最長公共子序列 (動態規劃)

POJ 1458/HDU 1159 最長公共子序列 (動態規劃)

題目連結:poj && hdu

程式碼

#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; }