UVA 10453
来源:互联网 发布:手机高中生 知乎 编辑:程序博客网 时间:2024/06/11 05:22
Description
By definition palindrome is a string which is not changed when reversed. "MADAM" is a nice example of palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be so easy to generate a palindrome.
Here we will make a palindrome generator which will take an input string and return a palindrome. You can easily verify that for a string of lengthn, no more than (n - 1) characters are required to make it a palindrome. Consider"abcd" and its palindrome "abcdcba" or "abc" and its palindrome "abcba". But life is not so easy for programmers!! We always want optimal cost. And you have to find the minimum number of characters required to make a given string to a palindrome if you are only allowed to insert characters at any position of the string.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a string of lowercase letters denoting the string for which we want to generate a palindrome. You may safely assume that the length of the string will be positive and no more than100.
Output
For each case, print the case number and the minimum number of characters required to make string to a palindrome.
Sample Input
6
abcd
aaaa
abc
aab
abababaabababa
pqrsabcdpqrs
Sample Output
Case 1: 3
Case 2: 0
Case 3: 2
Case 4: 1
Case 5: 0
Case 6: 9
题意:
给你一个字符串,要你求出最少插入多少个字符使得其为回文串.
思路:
求在已知的字符串中最少加上几个字母,可以使其变成回文字符串,a[i] == a[j]{dp[i][j] = dp[i+1][j-1];}
a[i] != a[j])dp[i][j] = min(dp[i+1][j],dp[i][j-1]) + 1;
代码:
#include <cstring>#include <cstdio>#include<algorithm>using namespace std;char a[103];int dp[103][103];int main(){ int n,tt=1; while(scanf("%d",&n)!=EOF) { for(int i=0;i<n;i++) { scanf("%s",a+1); int m=strlen(a+1); memset(dp,0,sizeof(dp)); for(int i=m-1;i>0;i--) for(int j=i+1;j<=m;j++) { if(a[i]==a[j]) dp[i][j]=dp[i+1][j-1]; else dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1; } printf("Case %d: %d\n",tt++,dp[1][m]); } } return 0;}
- UVA 10453
- UVA 10453
- uva 10453 Make Palindrome
- UVA 10453 Make Palindrome
- UVA 10453 Make Palindrome
- UVA 10453 Make Palindrome
- UVA - 10453 Make Palindrome
- UVa:10453 Make Palindrome
- uva 10453 - Make Palindrome
- UVA 10453 - Make Palindrome
- uva 10453(dp)
- UVA - 10453 Make Palindrome
- UVA - 10453 Make Palindrome
- uva 10453 dp
- uva 10453 Make Palindrome
- UVa 10453 - Make Palindrome
- uva
- UVA
- 黑马程序员----接口(interface)
- 裁减图片
- win8.1 和VC++ 6.0的兼容问题解决
- 《高质量C编程指南》--读书笔记
- 2015年流行的网页设计趋势
- UVA 10453
- feof与块读写
- Android透明状态栏(沉浸式状态栏)
- Jzzhu and Sequences (周赛3)
- ECShop模板中smarty foreach标签详解
- 金蝶EAS BOS如何实现特殊数据授权
- 修改input file文件上传的默认样式
- Apache & Nginx
- 杭州电子科技大学acm--2006