In this problem you are asked to convert a string into a palindrome with minimum number of operations. The operations are described below:
Here you’d have the ultimate freedom. You are allowed to:
- Add any character at any position
- Remove any character from any position
- Replace any character at any position with another character
Every operation you do on the string would count for a unit cost. You’d have to keep that as low as possible.
For example, to convert “abccda” you would need at least two operations if we allowed you only to add characters. But when you have the option to replace any character you can do it with only one operation. We hope you’d be able to use this feature to your advantage.
Input
The input file contains several test cases. The first line of the input gives you the number of test cases, T (1≤T≤10). Then T test cases will follow, each in one line. The input for each test case consists of a string containing lower case letters only. You can safely assume that the length of this string will not exceed 1000 characters.
Output
For each set of input print the test case number first. Then print the minimum number of characters needed to turn the given string into a palindrome.
Sample Input Output for Sample Input
6 tanbirahmed shahriarmanzoor monirulhasan syedmonowarhossain sadrulhabibchowdhury mohammadsajjadhossain | Case 1: 5 Case 2: 7 Case 3: 6 Case 4: 8 Case 5: 8 Case 6: 8 |
//f(i,j)表示从串的i到j最少需要多少操作
//然而增加和删除的操作产生的效果一样,所以只要考虑一种即可
//这里只考虑删除 所以f(i,j) = f(i+1,j-1) s[i] == s[j];
// min(f(i+1,j)+1,f(i,j-1)+1,f(i+1,j-1)+1); 其中前两个代表删除,后两个代表替换
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <string>
#include <climits>
#include <sstream>
#define sf scanf
#define pf printf
#define fir first
#define sec second
#define pd push_back
#define cls(a,x) (memset(a,x,sizeof(a)))
#if(defined(_WIN32) || defined(__WIN32__))
typedef __int64 LL;
typedef unsigned __int64 ULL;
#define ll I64
#else
typedef long long LL;
typedef unsigned long long ULL;
#define I64 ll
#endif
template <class T>inline void scaf(T &v){
char ch;
while(ch = getchar())
{
if(ch >= '0' && ch <= '9')
break;
}
v = ch - '0';
while(ch = getchar())
{
if(ch >= '0' && ch <= '9')
v = (v<<1) + (v<<3) + ch - '0';
else
break;
}
}
using namespace std;
#define maxn 1010
#define min(a,b) (a) < (b) ? (a) : (b)
char s[maxn];
int f[maxn][maxn];
int dp(int i, int j){
if(i > j)
return 0;
int &ans = f[i][j];
if(ans != -1)
return ans;
if(i == j)
return ans = 0;
ans = 0;
if(s[i] == s[j])
ans = dp(i + 1, j - 1);
else
{
ans = dp(i + 1, j - 1) + 1;
if(ans > dp(i + 1, j) + 1)
ans = dp(i + 1, j) + 1;
if(ans > dp(i, j - 1) + 1)
ans = dp(i, j - 1) + 1;
}
return ans;
}
int main(void){
int t;
sf("%d", &t);
int kCase = 0;
while(t--)
{
sf("%s", s);
cls(f, -1);
pf("Case %d: %d\n", ++kCase, dp(0, strlen(s) - 1));
}
return 0;
}