Original title:
In the problem you is asked to convert a string into a palindrome with minimum number of OP Erations.
The operations is described below:
Here you ' d has the ultimate freedom. You is allowed to:
Add any character at any position
remove all character from any position
replace Any character to position with another character
every operation you do on the string would count of a unit cost . You ' d has to keep the as low
as possible.
For example, to-convert "ABCCDA" would need at least-operations if we allowed you only to
add characters . If you had the option to replace any character you can do it with only one
operation. We hope you ' d is able to the use of this feature to your advantage.
The main idea:
give you a string, let you arbitrarily add, delete, replace, ask you at least how many steps can turn this string into a palindrome.
#include <iostream> #include <algorithm> #include <map> #include <string> #include <cstring > #include <sstream> #include <cstdio> #include <vector> #include <cmath> #include <stack
> #include <queue> #include <iomanip> #include <set> #include <fstream> using namespace std;
int dp[1001][1001];
int min3 (int x,int y,int z) {return min (min (x, y), Min (x,z)),} int main () {Ios::sync_with_stdio (false);
int n;
string S;
cin>>n;
for (int k=1;k<=n;k++) {cin>>s;
Memset (Dp,0,sizeof (DP)); for (int i=s.size () -1;i>=0;i--) {for (int j=i+1;j<s.size (); j + +) {if (
S[I]==S[J]) dp[i][j]=dp[i+1][j-1];
else Dp[i][j]=min3 (dp[i+1][j],dp[i][j-1],dp[i+1][j-1]) +1;
}} cout<< "Case" <<k<< ":" <<dp[0][s.size () -1]<<endl; }//Input.close ();
Output.close ();
return 0;
}
Answer:
First of all you can think of this is an interval of dynamic programming problems, simply consider a direction of the optimal solution is not considered. Now consider two directions, that is, set DP[I][J] to indicate the number of steps that the palindrome of this part of I to J requires the least amount of action.
Next consider the state transfer, the problem given in the state transfer there are 3 ways to add, replace, delete. The effect of adding and deleting is the same, and each increment or deletion is to form a palindrome string, for example, in string si....sj, Dp[i][j] =dp[i][j-1]+1 can be expressed as deleting the J, It can also be expressed as adding a character to the front of I (note that at this point Si becomes si+1). If the substitution is to force the first character and the first J character to be the same, that is dp[i][j]=dp[i+1][j-1]+1. So the transfer equation would be Dp[i][j]=min (Dp[i+1][j],dp[i][j-1],dp[i+1][j-1]) +1 (when S[i]!=s[j]).