uva_10453 - Make Palindrome(普通DP)

Here Set dp[i][j] -> change str[i...j] into a palindrome min cost.
                dp[i+1][j-1] (str[i] == str[j])
dp[i][j] = min  min(dp[i+1][j], dp[i][j-1])+1
ans = dp[i][j]

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

#define INIT    -1
#define MID      0
#define LEFT     1
#define RIGHT    2
#define MAXN     1001

char str[MAXN];
int  dp[MAXN][MAXN], pre[MAXN][MAXN];

void back_trace(const int &l, const int &r)
{
        if( INIT == pre[l][r] ) {
                if( l == r ) {
                        printf("%c", str[l]);
                }
                return ;
        }
        if( MID == pre[l][r] ) {
                printf("%c", str[l]); back_trace(l+1, r-1); printf("%c", str[r]);
        }
        if( LEFT == pre[l][r] ) {
                printf("%c", str[l]); back_trace(l+1, r); printf("%c", str[l]);
        }
        if( RIGHT == pre[l][r] ) {
                printf("%c", str[r]); back_trace(l, r-1); printf("%c", str[r]);
        }
}

int recusion(const int &l, const int &r)
{
        if( l >= r ) {
                return 0;
        }
        if( INIT != dp[l][r] ) {
                return dp[l][r];
        }
        if( str[l] == str[r] ) {
                pre[l][r] = MID; return dp[l][r] = recusion(l+1, r-1);
        }
        if( recusion(l+1, r) > recusion(l, r-1) ) {
                pre[l][r] = RIGHT; return dp[l][r] = recusion(l, r-1)+1;
        }
        pre[l][r] = LEFT; return dp[l][r] = recusion(l+1, r)+1;
}

int main(int argc, char *argv[])
{
#ifndef ONLINE_JUDGE
        freopen("test.in", "r", stdin);
#endif
        while( ~scanf("%s", str) ) {
                for(int i = 0; i < strlen(str); i ++) {
                        memset(dp[i], INIT, sizeof(int)*(strlen(str)+1));
                        memset(pre[i], INIT, sizeof(int)*(strlen(str)+1));
                }
                printf("%d ", recusion(0, strlen(str)-1)); back_trace(0, strlen(str)-1); printf("\n");           
        }
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值