POJ 1159:Palindrome ← 区间DP + 滚动数组 + LCS
【题目来源】
【题目描述】
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.
中文大意:回文是一个对称的字符串,即从左向右读和从右向左读都能得到相同的字符串。你需要编写一个程序,输入一个字符串后,计算出需要在该字符串中插入多少个字符才能使其成为回文。
例如,通过插入 2 个字符,字符串“Ab3bd”可以转换为回文(“dAb3bAd”或“Adb3bdA”)。然而,插入少于 2 个字符则无法得到回文。
【输入格式】
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.
中文大意:您的程序应从标准输入读取数据。第一行包含一个整数:输入字符串的长度 N,3 <= N <= 5000。第二行包含一个长度为 N 的字符串。该字符串由从 'A' 到 'Z' 的大写字母、从 'a' 到 'z' 的小写字母以及从 '0' 到 '9' 的数字组成。大写字母和小写字母应被视为不同的字符。
【输出格式】
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
中文大意:您的任务是将内容输出到标准输出设备。第一行包含一个整数,该整数即为所需的最小值。
【输入样例】
5
Ab3bd
【输出样例】
2
【数据范围】
3 <= N <= 5000
【算法分析】
● 滚动数组:
通过滚动数组技术可将空间复杂度从 O(N) 优化至 O(1),从而可在内存限制下完成计算。
● 当 N=5000 时,若直接声明 int a[5000][5000],由于每个 int 元素通常占 4 字节,故此 int 数组约占内存 5000×5000×4÷1024÷1024≈95.37MB。若声明 short a[5000][5000],由于每个 short 元素通常占 2 字节,故此 short 数组约占内存 5000×5000×2÷1024÷1024≈47.68MB。在部分严格的内存限制(如 64 MB)或栈空间限制下,此 int 数组会导致内存超限(MLE)或栈溢出。
一种解决方案,利用 short 数组则可能恰好通过。另外一种解决方案,就是利用“滚动数组”进行优化。
● 本文把「求字符串最少插入字符成回文」的问题,转化为「最长公共子序列 (LCS)」的问题。之后,用奇偶滚动数组做极致空间优化。代码短小但含金量极高。主要依据一下两个核心点。
(1)字符串构建回文串的最少插入字符数 = 字符串长度 - 字符串最长回文子序列 (LPS) 的长度
(2)字符串的最长回文子序列 (LPS) = 字符串与其逆序字符串的最长公共子序列 (LCS)
【算法代码】
【参考文献】

浙公网安备 33010602011771号