动态规划+滚动数组 -- POJ 1159 Palindrome
来源:互联网 发布:卧龙01灵宝进阶数据 编辑:程序博客网 时间:2024/05/16 14:28
给一字符串,问最少加几个字符可以让它成为回文串,
比如 Ab3bd 最少需要两个字符可以成为回文串 dAb3bAd
思路:
动态规划 DP[i][j] 意味着从 i 到 j 这段字符变为回文串最少要几个字符,枚举子串长。
if str[i] == str[j]:
DP[i][j] = DP[i + 1][j - 1]
else:
DP[i][j] = min( DP[i + 1][j], DP[i][j - 1] ) + 1
注意:
长度较大为 5000,二维数组 5000 * 5000 需要将类型改为 short,
不需考虑 j - i < 2 的特殊情况,
因为矩阵的左下三角形会将DP[i + 1][j - 1]自动填零,
但是用滚动数组的时候需要考虑 j - i < 2,用滚动数组的时候,空间会变为 3 * 5000,
可这时候 DP 的含义稍微变下,
DP[i][j] 意味着从第 j 个字符右移 i 个长度的字符串变为回文串所需要的最少字符数目。
3.也可以用 LCS 的方法,字符串长 - LCS( 串,逆串 )
#include <iostream>#include <cstring>using namespace std;int nLen;char str[5005];short DP[5005][5005];int main(){ memset( DP, 0, sizeof( DP ) ); cin >> nLen; cin >> str; for( int len = 1; len < nLen; ++len ){ for( int start = 0; start + len < nLen; ++start ){ int end = start + len; if( str[start] == str[end] ) DP[start][end] = DP[start + 1][end - 1]; else DP[start][end] = min( DP[start + 1][end], DP[start][end - 1] ) + 1; } } cout << DP[0][nLen - 1]; return 0;}
滚动数组 715K:
#include <iostream>#include <cstring>using namespace std;int nLen;char str[5005];short DP[3][5005];int main(){ memset( DP, 0, sizeof( DP ) ); cin >> nLen; cin >> str; for( int len = 1; len < nLen; ++len ){ for( int start = 0; start + len < nLen; ++start ){ int end = start + len; if( str[start] == str[end] && ( end - start >= 2 ) ) DP[len % 3][start] = DP[( len - 2 ) % 3][start + 1]; else if( str[start] != str[end] ) DP[len % 3][start] = min( DP[( len - 1 ) % 3][start + 1], DP[( len - 1 ) % 3][start] ) + 1; } } cout << DP[(nLen - 1) % 3][0]; return 0;}
2 0
- POJ 1159 Palindrome 动态规划+滚动数组
- 动态规划+滚动数组 -- POJ 1159 Palindrome
- poj1159 palindrome(动态规划+滚动数组)
- POJ1159 Palindrome 动态规划+滚动数组
- POJ 1159 Palindrome(滚动数组)
- Palindrome POJ 1159 动态规划
- poj 1159 Palindrome 动态规划
- 【动态规划】【poj 1159】palindrome
- poj 1159 palindrome-----动态规划
- HDU ACM 1513 Palindrome->动态规划(滚动数组)
- poj-1159-Palindrome-学习滚动数组
- poj 1159 Palindrome 【LCS + 滚动数组】
- POJ 1159 Palindrome DP 滚动数组
- hdu1513&&poj 1159 Palindrome(LCS+滚动数组)
- poj 1159 Palindrome lcs+滚动数组
- poj 1159 Palindrome ( dp 滚动数组 )
- Poj 1159-Palindrome DP (滚动数组优化)
- poj - 1159 - Palindrome(滚动数组dp)
- 双目相机的畸变校正以及平行校正(极线校正)的入门问题总结
- OBJECTIVE-C中nsstring的writetofile atomically参数解释
- c++ const,引用,STL容器
- Swift语言从天而降,能否掀起新一轮的科技革命?
- C语言学习随笔
- 动态规划+滚动数组 -- POJ 1159 Palindrome
- hdu 1788
- 用sql 注销远程脚本
- Fibonacci数列 3
- 爱上了我的司机(2)
- Handler中的一些总结
- B - Adding Reversed Numbers(4.2.1)
- [leetcode] Maximum Subarray
- 常用变量缩写对照表