UVA 10739 String to Palindrome(dp)

来源:互联网 发布:国外手机直播软件 编辑:程序博客网 时间:2024/04/29 02:40

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


题意:给定一个字符串,可以进行添加,删除,和替换操作,求最少操作数使得该串变成回文串。

思路:i,j作为字符串的头尾。添加和删除操作其实是一样的。所以只需要考虑2种状态的转移了。

状态转移方程如果str[i] == str[j]则满足回文不用转换。dp[i][j] = dp[i + 1][j - 1]

如果不相等:dp[i][j] = min(min(dp[i + 1][j], dp[i][j - 1]), dp[i + 1][j - 1]) + 1

由于是递推。所以要从后往前。

代码:

#include <stdio.h>#include <string.h>int t, i, j, dp[1005][1005], len;char sb[1005];int min(int a, int b) {return a < b ? a : b;}int main() {scanf("%d%*c", &t);int tt = 1;while (t --) {memset(dp, 0, sizeof(dp));gets(sb);len = strlen(sb);for (i = len - 1; i >= 0; i --) {for (j = i + 1; j < len; j ++) {if (sb[i] == sb[j])dp[i][j] = dp[i + 1][j - 1];elsedp[i][j] = min(min(dp[i + 1][j], dp[i][j - 1]), dp[i + 1][j - 1]) + 1;}}printf("Case %d: %d\n", tt ++, dp[0][len - 1]);}return 0;}



原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 发票货物名称多怎么办 发票上少打一个字怎么办 发票名称带星号怎么办 小贷太多还不上怎么办 生日当天买保险怎么办 我挪用公司货款怎么办 车辆改名字保险怎么办 工伤报案周六日怎么办 五菱宏光s1门下沉怎么办 新手机版本更新怎么办 戴尔电脑开机黑屏怎么办 淘宝退货不发货怎么办 铝被酸腐蚀怎么办 新娘头饰氧化了怎么办 合金饰品变黑了怎么办 麻醉机fico2升高怎么办 快递被恶意投诉怎么办 顺风快递收件人拒收怎么办 手机联系人没了怎么办 收件人号码错了怎么办 收件人写错了怎么办 快递联系不到收件人怎么办 小孩烫伤有水泡怎么办 被烫伤的疤痕怎么办 微店别人下单后怎么办 月经超了七天怎么办 收件人不在指定地址怎么办 2017款宝来熄火后异响怎么办 我身高一八米怎么办呀 规格型号错了发票怎么办 合同签错了怎么办 柜子背板起泡怎么办啊 显卡红灯不亮怎么办 小米设置全英文怎么办 小米手机变英文怎么办 阿迪贝壳头变黄怎么办 网友问我名字怎么办 护照姓名拼写错误怎么办 cfa报名时填错名字怎么办 机票拼音错了怎么办 evus忘填了怎么办