51NOD 1092 回文字符串 LCS
2024-08-27 18:02:49
Q:给定一个串,问需要插入多少字符才能使其成为回文串,也就是左右对称的串。
经典求LCS题,即最长公共子序列,不用连续的序列。考虑O(n2)解法,求LCS起码得有两个串,题中才给了一个串,另一个需要自己造,将给定的串反置,然后求这两个串的LCS。假设两个串为str1和str2,想办法将规模降低,分两种情况考虑:
- str1[i]==str2[j],则dp[i][j] = dp[i-1][j-1] + 1,其中dp[i][j]表示str1[1i]与str2[1j]的最长公共子序列长度。
- str1[i]!=str2[j],则dp[i][j] = max(dp[i-1][j], dp[i][j-1])。
这其实就是用小规模来推出稍大规模的解,也就是DP思想了。所求得的LCS就是最长回文子序列的长度了,没有包含在LCS中的字符都是需要为它们插入一份拷贝的。答案自然就是size-lcs
。
#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int dp[N][N];
char str[N], cpy[N];
int MaxMirrorSeq(char *sp, int size)
{
memcpy(cpy, sp, size+2);
reverse(cpy+1, cpy+1+size); //反置
memset(dp, 0, sizeof(dp));
int ans = 0;
for(int i=1; i<=size; i++)
{
for(int j=1; j<=size; j++)
{
if(str[i]==cpy[j]) dp[i][j] = dp[i-1][j-1]+1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
ans = max(ans, dp[i][j]);
}
}
return ans;
}
int main()
{
freopen("input.txt", "r", stdin);
while(~scanf("%s", str+1)) {
int size = strlen(str+1);
cout<<size-MaxMirrorSeq(str, size)<<endl;
}
return 0;
}
最新文章
- Android开发环境的搭建
- Express安装过程
- C#的输入、输出与运算符、数据类型
- 【读书笔记】iOS-UIFont-如何知道字体的PostScript名称
- python中的is、==和cmp()比较字符串
- LED驱动简单设计
- [再寄小读者之数学篇](2014-12-04 $\left(1+\frac{1}{x}\right)^x>;\frac{2ex}{2x+1},\forall\ x>;0.$)
- lintcode:最大子数组差
- pyshp操作shapefile
- SQL Server 2008 远程过程调用失败[ VS2012]
- linux性能调优概述
- Safecracker
- openstack使用openvswitch实现vxlan组网
- [笔记]猿计划(WEB安全工程师养成之路系列教程):03HTML基础标签
- tensorflow_目标识别object_detection_api,RuntimeError: main thread is not in main loop,fig = plt.figure(frameon=False)_tkinter.TclError: no display name and no $DISPLAY environment variable
- js的数据类型:单例模式,工厂模式,构造函数
- SpringMVC的工作流程、组件说明以及常用注解说明
- uva 1322 Minimizing Maximizer
- Numpy:ndarray数据类型和运算
- JSON草稿
热门文章
- Python字符串拼接、格式化输出、深浅复制
- CodeForces - 593A -2Char(思维+暴力枚举)
- 第五章:引用类型(一)-Object和Array
- Java日志组件1---Jdk自带Logger(java.util.logging.Logger)
- C# Linq 查询数据库(DataSet)生成 Tree
- Java 实践
- [转]AngularJS+UI Router(1) 多步表单
- express中connect-flash中间件的使用
- 使用Xshell连接服务器
- pat04-树7. Search in a Binary Search Tree (25)