HDU-2476-String painter

来源:互联网 发布:淘宝卖电子资料处罚 编辑:程序博客网 时间:2024/06/06 00:49

ACM模版

描述

描述

题解

区间 dp 套路深啊~~~

首先我们假设用一个空白串儿进行区间 dp 来刷成 B 串。然后我们开始遍历两串,如果 A[i]=B[i],那么 ans[i]=ans[i1],否则的话,就需要利用前边处理出来的 dp[][] 来进行进一步 dp 了,这里的 dp[i][j] 表示由一个空白串儿从 ij 区间刷成 B 串的最少处理次数。

代码

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;const int MAXN = 111;char A[MAXN];char B[MAXN];int ans[MAXN];int dp[MAXN][MAXN];int main(int argc, const char * argv[]){    while (cin >> A >> B)    {        memset(dp, 0, sizeof(dp));        memset(ans, 0, sizeof(ans));        int len = (int)strlen(A);        for (int i = 0; i < len; i++)        {            dp[i][i] = 1;        }        for (int i = 1; i < len; i++)           //  区间长度        {            for (int j = 0; j + i < len; j++)   //  区间起始位置            {                int r = i + j;                  //  区间终点位置                dp[j][r] = dp[j + 1][r] + 1;                for (int k = j + 1; k <= r; k++)//  遍历区间                {                    if (B[j] == B[k])                    {                        dp[j][r] = min(dp[j][r], dp[j + 1][k] + dp[k + 1][r]);                    }                }            }        }        if (A[0] != B[0])        {            ans[0] = 1;        }        for (int i = 1; i < len; i++)        {            if (A[i] == B[i])            {                ans[i] = ans[i - 1];            }            else            {                ans[i] = dp[0][i];                for (int j = 0; j < i; j++)                {                    ans[i] = min(ans[i], ans[j] + dp[j + 1][i]);                }            }        }        printf("%d\n", ans[len - 1]);    }    return 0;}