首页 > 代码库 > poj 1458 Common Subsequence

poj 1458 Common Subsequence

题目链接:http://poj.org/problem?id=1458

 

思路:

    经典的最长公共子序列问题,使用动态规划解题。

代码:

 

#include <iostream>#include <string.h>using namespace std;const int MAX_N = 200 + 10;int dp[MAX_N][MAX_N];char X[MAX_N], Y[MAX_N];void Lcs( int XLen, int YLen ){    for ( int i = 1; i <= XLen; ++i )        for( int j = 1; j <= YLen; ++j )        {            if ( X[i-1] == Y[j-1] )                dp[i][j] = dp[i-1][j-1] + 1;            else            if ( dp[i-1][j] >= dp[i][j-1] )                dp[i][j] = dp[i-1][j];            else                dp[i][j] = dp[i][j-1];        }}int main(){    while ( scanf( "%s %s", X, Y ) != EOF )    {        int XLen, YLen;        memset( dp, 0, sizeof(dp) );        XLen = strlen( X );        YLen = strlen( Y );        Lcs( XLen, YLen );        printf( "%d\n", dp[XLen][YLen] );    }    return 0;}

 

poj 1458 Common Subsequence