hdu 1503 + 简单dp ( 最长公共子序列型)+记忆化搜索+stl

没啥好说,模板题

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <string>
#define MAX 107

using namespace std;

int dp[MAX][MAX];
string s[MAX][MAX];
char s1[MAX] , s2[MAX];

void dfs ( int i , int j )
{
    if ( dp[i][j] != -1 )  return;
    if ( i== 0 && j== 0 )
    {
        dp[i][j] = 0;
        s[i][j]  = "";
        return;
    }
    if ( i >= 1 && j >= 1 && s1[i] == s2[j] )
    {
        if ( dp[i-1][j-1] == -1 ) dfs (  i-1 , j-1 );
        if ( dp[i][j] != -1 && dp[i][j] > dp[i-1][j-1] + 1 )
            dp[i][j] =  dp[i-1][j-1]+1 ,s[i][j] = s[i-1][j-1] + s1[i];
        else if ( dp[i][j] == -1 ) 
            dp[i][j] = dp[i-1][j-1] + 1,s[i][j] = s[i-1][j-1]+ s1[i];
    }
    if ( i>=1 && dp[i-1][j] == -1 ) dfs ( i-1 , j );
    if ( j>=1 && dp[i][j-1] == -1 ) dfs ( i , j-1 );
    if ( i>=1 && ( dp[i][j] > dp[i-1][j]+1||dp[i][j] == -1 ) )
        dp[i][j] = dp[i-1][j]+1 , s[i][j]=s[i-1][j]+s1[i];
    if ( j>=1 && ( dp[i][j] > dp[i][j-1]+1||dp[i][j] == -1 ) )
        dp[i][j] = dp[i][j-1]+1 , s[i][j]=s[i][j-1]+s2[j];
}

int main ( )
{
    while ( ~scanf ( "%s" , s1+1 ) )
    {
        scanf ( "%s" , s2+1 );
        int len1 = strlen (s1+1);
        int len2 = strlen (s2+1);
        memset ( dp , -1 , sizeof ( dp ) );
        dfs ( len1 , len2 );
        cout << s[len1][len2] << endl;
    }
}


你可能感兴趣的:(C++,动态规划,最长公共子序列,记忆化搜索)