hdu-1513 Palindrome
2015-08-12 20:45
190 查看
Palindrome
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4157 Accepted Submission(s): 1420
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
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.
[align=left]Output[/align]
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
[align=left]Sample Input[/align]
5
Ab3bd
[align=left]Sample Output[/align]
2
与最长公共子串类似。
开始默认以字符串中间字母为对称轴,拆为两个字符串进行计算,之后用字符串长度减去相应地公共子串长度,wrong了好几发,没找到错误原因。
之后借鉴大神代码改了dp方程:
for (int i=n-2; i>=0; i--) {
for (int j=i+1; j<n; j++) {
if (s[i]==s[j]) {
lcs[i%2][j]=lcs[(i+1)%2][j-1];
}
else {
lcs[i%2][j]=min(lcs[(i+1)%2][j],lcs[i%2][j-1])+1;
}
}
}
dp方程中用到了滚动数组,防止5000*5000内存炸了。
dp方程内容与最长公共子串类似,但是将字符串分为两部分,计算公共字串。若两边字符相等,则dp[i][j]不变,否则取右方与上方最小值加一,表示需加入一个字符构成回文。
下面是代码:
#include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cstdlib> #include <string> #include <vector> #include <cstdio> #include <cmath> #include <queue> #include <stack> #include <map> #include <set> using namespace std; #define Max 200005 string s1,s2,s; int lcs[5][5505]; int main(){ int n; while (cin>>n) { cin>>s; memset(lcs, 0, sizeof(lcs)); for (int i=n-2; i>=0; i--) { for (int j=i+1; j<n; j++) { if (s[i]==s[j]) { lcs[i%2][j]=lcs[(i+1)%2][j-1]; } else { lcs[i%2][j]=min(lcs[(i+1)%2][j],lcs[i%2][j-1])+1; } } } cout<<lcs[0][n-1]<<endl; } return 0; }
相关文章推荐
- URL和HTTPClient与服务器的连接
- iOS中的内存管理1
- failed to load resource file osql.rll
- 很容易学习的JQuery库 : (一) 简介
- Oracle LOB数据类型专题
- 【leetcode】【Numbers of 1 bits】java >>> &符号
- 用PDB库调试Python程序
- Sudoku
- 用proc实时管理 Linux
- vc++6对windows SEH扩展分析 一文拾遗
- ORM进阶之Hibernate 简介及框架搭
- Python+NLTK自然语言处理学习(一):环境搭建
- HDU5371——Manacher+set维护——Hotaru's problem
- Sudoku
- cloudstack delete zone
- Java日志框架——Logback的体系结构
- 蓝桥杯-基础练习-大数算法
- 小知识点 - 串口输出数
- ScrollView
- 搜索引擎核心读书心得2:暗网抓取