hdu1513 Palindrome
来源:互联网 发布:spring 事务源码 编辑:程序博客网 时间:2024/06/06 21:00
Problem 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
这题是最长公共子序列的一个变形,先求出所给字符串的逆字符串,然后求出最长公共自序,然后用n减去所求得的最大长度。
这里直接开dp[maxn][maxn]会超内存,所以用到滚动数组,因为每次只用到前2个,所以每次%2.
#include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<vector>#include<map>#include<queue>#include<stack>#include<string>#include<algorithm>using namespace std;#define maxn 5060int dp[2][maxn];char s1[maxn],s2[maxn];int main(){int n,m,i,j,x,y;while(scanf("%d",&n)!=EOF){scanf("%s",s1+1);for(i=1;i<=n;i++){s2[i]=s1[n+1-i];}memset(dp,0,sizeof(dp));for(i=1;i<=n;i++){for(j=1;j<=n;j++){x=i%2;y=1-x;if(s1[i]==s2[j]){dp[x][j]=dp[y][j-1]+1;}else{dp[x][j]=max(dp[x][j-1],dp[y][j]);}}}printf("%d\n",n-dp[n%2][n]);}return 0;}
0 0
- HDU1513:Palindrome
- hdu1513 Palindrome
- 【HDU1513】【Palindrome】
- HDU1513:Palindrome
- hdu1513 Palindrome
- HDU1513 && POJ1159:Palindrome(LCS)
- Palindrome(hdu1513(LCS))
- hdu1513——Palindrome
- hdu1513 Palindrome 动态规划
- HDU1513:Palindrome 【LCS】
- HDU1513 Palindrome(LCS+滚动数组)
- hdu1513&&poj 1159 Palindrome(LCS+滚动数组)
- HDU1513 && POJ1159 Palindrome 最长公共子序列
- hdu1513 Palindrome(LCS+滚动数组)
- hdu1513
- Palindrome(补全回文串+最长公共子序列的应用)hdu1513+poj1159+动态规划
- hdu1513 dp
- hdu1513滚动数组
- JBoss调优(四)web服务器线程池调优
- linux i2c总线协议(一)
- CSS编码规范
- Java多线程服务端与客户端的交互小实例
- 面试中的红黑树问题
- hdu1513 Palindrome
- 【Android】Android客户端以线程的方式从服务器的PHP读取Mysql
- rop 入门(五)
- leetcode longestCommonPrefix
- curl 命令使用
- Objective-C中的NSValue的详解
- eclipse快捷键-超实用
- HDU3652 B-number
- Android应用经典主界面框架之二:仿网易新闻客户端、CSDN 客户端 (Fragment ViewPager)