Problem H
String to Palindrome
Input: Standard Input
Output: Standard Output
Time Limit: 1 Second
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 |
这道题是典型的的区间dp,用dp[i][j]表示s[i]...s[j]变成回文串的最少修改次数。
如果s[i]==s[j],那么dp[i][j]=dp[i+1][j-1],这个是显然的,如果dp[i][j]可以更少,那么去掉s[i]和s[j],s[i+1]...s[j-1]可以有更少的修改次数,这与假设dp[i+1][j-1]是s[i+1]...s[j-1]变成回文串的最少修改次数相矛盾。
如果s[i]!=s[j],这个时候可以有三种修改方式了,在dp[i+1][j]基础上,删除s[i]或者加s[j+1]=s[i];在dp[i][j-1]基础上,删除s[j]或者加s[i-1]=s[j];在dp[i+1][j-1]基础上,修改s[i]=s[j]或者s[j]=s[i];既然要dp[i][j]最小,那么只要取三者最小,然后加上1次修改即可。
这道题要注意初始值,因为转移式中dp[i+1][j-1],要满足i+1<=j-1即i+2<=j,因此区间长度要从3开始哦,dp[i][i]=0,dp[i][i+1]=0,s[i]==s[i+1],否则dp[i][i+1]=1,s[i]!=s[i+1]。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#define Maxn 1010
using namespace std;
char s[Maxn];
int dp[Maxn][Maxn];
int main()
{
int t,cas=1;
scanf("%d",&t);
while(t--){
scanf("%s",s);
int n=strlen(s);
for(int i=0;i<n;++i){
dp[i][i]=0;
if(s[i]==s[i+1]) dp[i][i+1]=0;
else dp[i][i+1]=1;
}
for(int len=2;len<n;++len)
for(int i=0,j=len;j<n;++i,++j)
if(s[i]==s[j]) dp[i][j]=dp[i+1][j-1];
else dp[i][j]=min(dp[i+1][j-1],min(dp[i+1][j],dp[i][j-1]))+1;
printf("Case %d: %d\n",cas++,dp[0][n-1]);
}
return 0;
}