您的位置:首页 > 其它

uva_10453 - Make Palindrome(普通DP)

2012-11-29 15:09 381 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: