poj 1159 Palindrome
来源:互联网 发布:淘宝店铺怎样快速升级 编辑:程序博客网 时间:2024/06/06 18:35
Palindrome
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 52716 Accepted: 18187
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
Source
IOI 2000
【题意】加入最少的字符使字符串左右对称
【思路】dp[i][j]表示使第i位到第j位的字符串对称所需的最小字符数
状态转移方程:
dp[i][j]=dp[i+1][j-1] ch[i]==ch[j]
dp[i][j]=max(dp[i+1][j]+1,dp[i][j-1]+1) ch[i]!=ch[j];
此题不难,但是直接开dp[5000][5000]会超内存,就用滚动数组,这个滚动数组有三个,有点少见。。
【代码】
#include<cstdio>#include<cstring>#include<iostream>using namespace std;int dp[5010][3];char ch[5010];int main(){ int n; while(scanf("%d",&n)!=EOF) { scanf("%s",ch+1); memset(dp,0,sizeof(dp)); int e=0; for(int len=2;len<=n;len++) { e=(e+1)%3;//对3取余 for(int i=1;i<=n;i++) { int j=i+len-1; if(j>n)break; if(ch[i]==ch[j]) { if(i+1<=j-1)dp[i][e]=dp[i+1][(e+1)%3]; else dp[i][e]=0; } else { dp[i][e]=min(dp[i][(e+2)%3]+1,dp[i+1][(e+2)%3]+1); } } } printf("%d\n",dp[1][e]); } return 0;}
0 0
- poj 1159 Palindrome LCS
- poj 1159 Palindrome LCS
- poj 1159 Palindrome
- poj 1159 Palindrome
- dp poj 1159 Palindrome
- poj 1159 Palindrome
- poj 1159 Palindrome
- POJ 1159 Palindrome DP
- Palindrome poj 1159
- Poj 1159 Palindrome
- poj 1159 Palindrome
- poj 1159 Palindrome 【DP】
- poj 1159Palindrome
- poj 1159 Palindrome
- POJ 1159 Palindrome
- POJ 1159 Palindrome
- Poj 1159 Palindrome
- POJ 1159 Palindrome
- osg名词解释
- 查看Ubuntu/Redhat等Linux系统版本号等系统信息
- 零基础如何学习 Web 安全?
- JSP+SERVLET实现后登陆用户挤掉之前登录用户
- Java版选择排序的实现
- poj 1159 Palindrome
- 这个更新需要花去 50.6 M 磁盘上总计 /boot 的空间。请在 7737k 磁盘上留出 /boot 空间。清空您的回收站和临时文件,用“sudo apt-get clean
- Spring各个jar包的简介
- 设计模式之迭代器模式
- ArcGIS for JavaScript 开发GP服务思路解析
- 组装自己的tesla超级计算机
- 开源 免费 java CMS - FreeCMS2.0 个人资料
- Android系统源代码阅读指南
- 代理模式深入(一)——静态到动态