51Nod 编辑距离 DP+滚动数组

51Nod 编辑距离 DP

题目链接: 51Nod编辑距离
思路:令dp[i][j] 表示 A字符串前i个字符,与B字符串的前j个字符的最小编辑距离。
那么有,
  • i = 0 && j == 0 时, dp[i][j] = 0;
  • i = 0 && 0 < j < lenB时, dp[i][j] = j;
  •  j = 0 && 0 < i < lenA 时, dp[i][j] = i;
  • 0 < i < lenA && 0 < j < lenB时
    • if (A[i] == B[j]) dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1]) + 1);
    •  else dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
然后,第i行的结果只与i-1,和i行的结果有关,可以采用一个dp[2][MAXLENB]滚动数组来优化空间。
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

//#pragma comment(linker, "/STACK:1024000000,1024000000")

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)

typedef __int64  LL;
//typedef long long LL;
typedef unsigned int uint;
typedef pair PII;
typedef pair PLL;

const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 1000 + 5;
const int MAXM = 1000 + 5;

char A[MAXN], B[MAXN];
int dp[2][MAXN];

int main() {
#ifndef ONLINE_JUDGE
    FIN;
#endif // ONLINE_JUDGE
    while (~scanf("%s %s", A, B)) {
        int lenA = strlen(A);
        int lenB = strlen(B);
        for (int i = 0; i <= lenA; i++) {
            for (int j = 0; j <= lenB; j++) {
                if (i == 0 && j == 0) dp[i & 1][j] = 0;
                else if (i == 0) dp[i & 1][j] = j;
                else if (j == 0) dp[i & 1][j] = i;
                else if (A[i - 1] == B[j - 1]) dp[i & 1][j] = min(dp[(i - 1) & 1][j - 1], min(dp[(i - 1) & 1][j], dp[i & 1][j - 1]) + 1);
                else dp[i & 1][j] = min(dp[(i - 1) & 1][j - 1], min(dp[(i - 1) & 1][j], dp[i & 1][j - 1])) + 1;
            }
        }
        printf("%d\n", dp[lenA & 1][lenB]);
    }
    return 0;
}


你可能感兴趣的:(ACM____动态规划)