POJ - 1458 DP (Longest Common Subsequence)

Common Subsequence

Topic meaning:

Multiple sets of data, each set of two strings, find the longest common subsequence.

Problem solving ideas:

dp[i][j] represents the longest common subsequence of the first i characters of the first string and the first j characters of the second string, then when a [ i ] == b [ j ] Time d p [ i ] [ j ] = m a x ( d p [ i ] [ j ] , d p [ i 1 ] [ j 1 ] + 1 ) ;
when a [ i ] ! = b [ j ] Time d p [ i ] [ j ] = m a x ( d p [ i ] [ j ] , m a x ( d p [ i 1 ] [ j ] , d p [ i ] [ j 1 ] ) ) ;

AC code:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 1000;
int dp[maxn + 5][maxn + 5];
char a[maxn + 5], b[maxn + 5];
int main() {
    while(scanf("%s%s", a + 1, b + 1) != EOF) {
        memset(dp, 0, sizeof(dp));
        int len1 = strlen(a + 1);
        int len2 = strlen(b + 1);
        for(int i = 1; i <= len1; i++)
            for(int j = 1; j <= len2; j++) {
                if(a[i] == b[j])dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
                else dp[i][j] = max(dp[i][j], max(dp[i - 1][j], dp[i][j - 1]));
            }
        printf("%d\n", dp[len1][len2]);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324892609&siteId=291194637