题意:给定一字符串,要求用最少的变换操作来使得该串变成回文串。
状态:dp[i][j]标识下标从i到j的子串变换成回文串所用的最少的步骤。
状态转移:dp[i][j] = min (dp[i+1][j],dp[i][j-1],dp[i+1][j-1]);
代码如下;
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define M 1005 int dp[M][M]; char s[M]; int main () { int t, cas = 0; scanf("%d",&t); while(cas++<t) { scanf("%s",s); int len = strlen(s); memset(dp,0,sizeof(dp)); for(int i = len-1; i >= 0; i--) for(int j = i+1; j < len; j++) { if(s[i]==s[j]) dp[i][j] = dp[i+1][j-1]; else { dp[i][j] = min(dp[i+1][j]+1,dp[i][j-1]+1); dp[i][j] = min(dp[i+1][j-1]+1,dp[i][j]); } } printf("Case %d: %d\n",cas,dp[0][len-1]); } }