题目链接:10453 - Make Palindrome

题目大意:给出一个字符串,通过插入字符使得原字符串变成一个回文串,要求插入的字符个数最小,并且输出最后生成的回文串。

解题思路:和uva 10739的做法相似,只是本题只能插入字符,所以只要在考虑子问题的同时记录住最优的选择就可以了。

#include <stdio.h>
#include <string.h>
const int N = 1005; int n, dp[N][N], rec[N][N];
char str[N]; int solve() {
n = strlen(str);
memset(dp, 0, sizeof(dp));
memset(rec, 0, sizeof(rec)); for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (str[i] == str[j])
dp[i][j] = dp[i + 1][j - 1];
else {
if (dp[i + 1][j] > dp[i][j - 1]) {
dp[i][j] = dp[i][j - 1] + 1;
rec[i][j] = 1;
}
else {
dp[i][j] = dp[i + 1][j] + 1;
rec[i][j] = -1;
}
}
}
}
return dp[0][n - 1];
} void print(int a, int b) {
if (a > b) return;
// printf("%d!\n", rec[a][b]);
if (a == b)
printf("%c", str[a]);
else if (rec[a][b] == 0) {
printf("%c", str[a]);
print(a + 1, b - 1);
printf("%c", str[a]);
}
else if (rec[a][b] == 1) {
printf("%c", str[b]);
print(a, b - 1);
printf("%c", str[b]);
}
else {
printf("%c", str[a]);
print(a + 1, b);
printf("%c", str[a]);
}
} int main() {
while (gets(str)) {
printf("%d ", solve());
print(0, n - 1);
printf("\n");
}
return 0;
}

最新文章

  1. IntelliJ IDEA 15.0.2远程debug tomcat
  2. jQuery 仿百度输入标签插件
  3. Python学习笔记——文件写入和读取
  4. 【分享】iTOP-4412开发板使用之初体验[多图]
  5. oracle wm_concat(column)函数的使用
  6. neutron 中 flat vlan gre vxlan的区别
  7. mvc 分页js
  8. Asp.Net MVC Views页面不包含“GetEnumerator”的公共定义
  9. java并发6-小结
  10. PHP初识
  11. ubuntu 配置jdk
  12. Numpy之ndarray与matrix
  13. Ubuntu14.04 工作区设置
  14. L2-010. 排座位
  15. 校验 MD5 值
  16. 下拉刷新和上拉加载 Swift
  17. linux系统编程之文件IO
  18. DataTable转实体类
  19. [jQuery]判断checkbox是否选中的3种方法
  20. Apache Spark技术实战之6 --Standalone部署模式下的临时文件清理

热门文章

  1. 解决C/C++程序执行一闪而过的方法(三种办法)
  2. Inno Setup 打包工具总结(转)
  3. codevs1166 矩阵取数游戏
  4. TransactionScope使用说明 【转】
  5. C / C++算法学习笔记(8)-SHELL排序
  6. ubuntu高版本环境变量问题
  7. asp.net application
  8. SQL Server插入中文数据后出现乱码
  9. SET STATISTICS IO和SET STATISTICS TIME 在SQL Server查询性能优化中的作用
  10. String.Empty、string=”” 和null的区别