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;
}

最新文章

  1. Android开发环境的搭建
  2. Express安装过程
  3. C#的输入、输出与运算符、数据类型
  4. 【读书笔记】iOS-UIFont-如何知道字体的PostScript名称
  5. python中的is、==和cmp()比较字符串
  6. LED驱动简单设计
  7. [再寄小读者之数学篇](2014-12-04 $\left(1+\frac{1}{x}\right)^x&gt;\frac{2ex}{2x+1},\forall\ x&gt;0.$)
  8. lintcode:最大子数组差
  9. pyshp操作shapefile
  10. SQL Server 2008 远程过程调用失败[ VS2012]
  11. linux性能调优概述
  12. Safecracker
  13. openstack使用openvswitch实现vxlan组网
  14. [笔记]猿计划(WEB安全工程师养成之路系列教程):03HTML基础标签
  15. 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
  16. js的数据类型:单例模式,工厂模式,构造函数
  17. SpringMVC的工作流程、组件说明以及常用注解说明
  18. uva 1322 Minimizing Maximizer
  19. Numpy:ndarray数据类型和运算
  20. JSON草稿

热门文章

  1. Python字符串拼接、格式化输出、深浅复制
  2. CodeForces - 593A -2Char(思维+暴力枚举)
  3. 第五章:引用类型(一)-Object和Array
  4. Java日志组件1---Jdk自带Logger(java.util.logging.Logger)
  5. C# Linq 查询数据库(DataSet)生成 Tree
  6. Java 实践
  7. [转]AngularJS+UI Router(1) 多步表单
  8. express中connect-flash中间件的使用
  9. 使用Xshell连接服务器
  10. pat04-树7. Search in a Binary Search Tree (25)