1、http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1680
2、题目大意:
给定一个字符串,可以对其做以下三种操作,增加一个字符,删除一个字符,替换一个字符,求出使得该字符串成回文串的最小操作步数,每种操作执行一次算一步
3、DP(x,y)表示比较到下标是x和下标是y时的最小的步数,最终结果为DP(0,len-1),正着和反着比较
if(str[x]==str[y])
dp[x][y]=DP(x+1,y+1);
if(str[x]!=str[y])
做删除操作,状态1+min(DP(x+1,y),DP(x,y-1))
做添加操作,状态1+DP(x+1,y-1)
做替换操作,状态1+DP(x+1,y-1)
4/AC代码:
#include<stdio.h>
#include<string.h>
#define N 1005
#include<algorithm>
using namespace std;
char str[N];
int visit[N][N];
int dp[N][N];
int DP(int x,int y)
{
if(visit[x][y])
return dp[x][y];
else if(x>=y)
{
visit[x][y]=1;
dp[x][y]=0;
return 0;
}
else
{
if(str[x]==str[y])
{
dp[x][y]=DP(x+1,y-1);
visit[x][y]=1;
}
else
{
dp[x][y]=1+min(min(DP(x+1,y),DP(x,y-1)),DP(x+1,y-1));
visit[x][y]=1;
return dp[x][y];
}
}
}
int main()
{
int t,cas=0;
scanf("%d",&t);
getchar();
while(t--)
{
cas++;
memset(visit,0,sizeof(visit));
memset(dp,0,sizeof(dp));
gets(str);
int len=strlen(str);
int ans=DP(0,len-1);
printf("Case %d: %d\n",cas,ans);
}
return 0;
}
/*
6
tanbirahmed
shahriarmanzoor
monirulhasan
syedmonowarhossain
sadrulhabibchowdhury
mohammadsajjadhossain
*/
4、题目;
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 |
Problem setter: Monirul Hasan, EPS