C: Palindrome Time limit: 1 S Memory Limit: 128 MB Title Description Given a string, you can make any changes to the string, you can add a character in any place, to delete a character or a character change. But the cost of different actions it takes are different, add and remove the price paid is 1, the direct cost of changing a character takes is 2, and asked how much it takes to get at least a palindrome string (string is palindrome left read right to left and right are the same, for example: ABCBA, HIH ...) input the first line of a next integer T-T set of data represents the next T lines each enter a string S (S length is less than 1000) output minimum cost problems is intended to meet the output of the sample input . 3 CHINESE MNBN JXUST sample output . 4 . 1 . 4
#include <bits/stdc++.h> using namespace std; int t,ls; #define N 1200 char s[N]; int dp[N][N]; int main() { scanf("%d",&t); while(t--){ scanf("%s",&s); ls=strlen(s); memset(dp,0,sizeof(dp)); for(int i =ls-1;i>=0;i--){ for(int j =i+1;j<ls;j++){ if(s[i]==s[j]) dp[i][j] = dp[i+1][j-1]; else{ dp[i][j] =min(min(dp[i+1][j]+1,dp[i][j-1]+1),dp[i+1][j-1]+2); //全按删除考虑 } } } printf("%d\n",dp[0][ls-1]); } return 0; }