POJ 1159 dp
来源:互联网 发布:广发淘宝卡集分宝 编辑:程序博客网 时间:2024/06/11 13:22
Palindrome
Time Limit: 3000MS Memory Limit: 65536K
Description
A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
Input
Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
Sample Input
5Ab3bd
Sample Output
2
题意:给你一个字符串,加入最少的字符,使其成为回文串。
题解:定义dp[i][j],为i到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;
else dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1;
由于5000*5000开不下,我们可以用滚动数组优化。
#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;char a[5005];int dp[2][5005];int main(){int i,j,n;scanf("%d",&n);scanf("%s",a);for(i=n-1;i>=0;i--){for(j=0;j<n;j++)dp[1][j]=dp[0][j];for(j=i+1;j<n;j++){if(a[i]==a[j])dp[0][j]=dp[1][j-1];else dp[0][j]=min(dp[1][j],dp[0][j-1])+1;}}printf("%d\n",dp[0][n-1]);return 0;}
0 0
- dp poj 1159 Palindrome
- POJ 1159 Palindrome DP
- poj 1159 Palindrome 【DP】
- POJ 1159 Palindrome dp
- POJ 1159 Palindrome(DP)
- POJ 1159 (DP)
- POJ 1159 Palindrome(DP)
- poj 1159 DP
- Palindrome - POJ 1159 dp
- POJ 1159 Palindrome DP
- 【DP】poj 1159_Palindrome_201408041527
- poj 1159 dp
- POJ 1159 Palindrome dp
- POJ-1159-Palindrome -dp
- [POJ 1159]Palindrome[DP]
- poj 1159 dp Palindrome
- POJ 1159 dp
- poj 1159(回文串dp)
- 瓶颈ing
- UI标签在火狐浏览器中某些问题解决
- zblog主题 www.gridsmedia.com
- 弹出窗口的两种实现方式 PopupWindow 和 Activity
- Zblog开源项目菜鸟集成之路(一)
- POJ 1159 dp
- JAVA算法题练习---01_提取不重复的整数
- sql语句那些事-- 临时表
- 标签总介绍
- 数据结构实验之链表九:双向链表
- HDU 4802 GPA(水题)
- 先序遍历+中序遍历还原二叉树(二)
- 写给初学前端工程师的一封信
- Centos 常用命令笔记