hdu 1503 记忆化搜索+递归输出+标记前驱

速度比stl版本快很多,0秒过...

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

using namespace std;

int dp[MAX][MAX];
//string s[MAX][MAX];
struct Pre
{
    int x , y;
    char c;
}pre[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;
        pre[i][j].x = -1;
        pre[i][j].y = -1;
        pre[i][j].c = 0;
        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 ,
            pre[i][j].x=i-1 , pre[i][j].y=j-1,
            pre[i][j].c = s1[i];
        else if ( dp[i][j] == -1 ) 
            dp[i][j] = dp[i-1][j-1],
            pre[i][j].x=i-1 , pre[i][j].y=j-1;
            pre[i][j].c = 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,
        pre[i][j].x = i-1 , pre[i][j].y = j,
        pre[i][j].c = 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 ,
        pre[i][j].x = i , pre[i][j].y = j-1,
        pre[i][j].c = s2[j];
}

void print ( int x , int y )
{
    if ( pre[x][y].x == -1 ) return;
    print ( pre[x][y].x , pre[x][y].y );
    printf ( "%c" , pre[x][y].c );
}   

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 );
        print ( len1 , len2 );
        puts ( "" );
    }
}


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