UVA 10739 String to Palindrome

UVA_10739

    我们用f[i][j]表示字符串从第i位到第j位构成回文串最少所需的操作数,如果b[i]==b[j],f[i][j]=f[i+1][j-1],否则f[i][j]=min{f[i][j-1],f[i+1][j],f[i+1][j-1]}+1。

#include<stdio.h>
#include<string.h>
#define MAXD 1010
#define INF 1000000000
char b[MAXD];
int f[MAXD][MAXD];
int dp(int x, int y)
{
int t, min = INF;
if(f[x][y] != -1)
return f[x][y];
if(x > y)
return 0;
if(b[x] == b[y])
{
t = dp(x + 1, y - 1);
if(t < min)
min = t;
}
else
{
t = dp(x + 1, y);
if(t + 1 < min)
min = t + 1;
t = dp(x, y - 1);
if(t + 1 < min)
min = t + 1;
t = dp(x + 1, y - 1);
if(t + 1 < min)
min = t + 1;
}
return f[x][y] = min;
}
void solve()
{
int k, res;
memset(f, -1, sizeof(f));
scanf("%s", b);
k = strlen(b) - 1;
res = dp(0, k);
printf("%d\n", res);
}
int main()
{
int t, tt;
scanf("%d", &t);
for(tt = 0; tt < t; tt ++)
{
printf("Case %d: ", tt + 1);
solve();
}
return 0;
}


你可能感兴趣的:(String)