51nod 1154 回文串划分(Manacher,dp)
发布日期:2021-11-02 09:48:37
浏览次数:7
分类:技术文章
本文共 1628 字,大约阅读时间需要 5 分钟。
1154 回文串划分
题目
有一个字符串S,求S最少可以被划分为多少个回文串。
例如:abbaabaa,有多种划分方式。a|bb|aabaa - 3 个回文串
a|bb|a|aba|a - 5 个回文串 a|b|b|a|a|b|a|a - 8 个回文串其中第1种划分方式的划分数量最少。
输入
输入字符串S(S的长度<= 5000)。
输出
输出最少的划分数量。
输入样例
abbaabaa
输出样例
3
#include#include #include #include #include using namespace std;const int maxn = 3e5;char s[maxn], str[maxn];// 初始长度,处理后长度int len1, len2;// 所有值,最大值int p[maxn], ans;// dp[i]:前 i 个数最少能变几个回文int dp[maxn];void init() { str[0] = '('; str[1] = '#'; for (int i = 0; i < len1; i++) { str[i * 2 + 2] = s[i]; str[i * 2 + 3] = '#'; } len2 = len1 * 2 + 2; str[len2] = ')';}void manacher() { int id = 0, mx = 0; for (int i = 1; i < len2; i++) { if (mx > i) p[i] = min(p[2 * id - i], mx - i); else p[i] = 1; while (str[i + p[i]] == str[i - p[i]]) p[i]++; if (p[i] + i > mx) { mx = p[i] + i; id = i; } }}int main() { while (scanf("%s", s) != EOF) { len1 = strlen(s); init(); manacher(); ans = 0; for (int i = 0; i < len1; i++) { dp[i] = i + 1; int pos = (i + 1) * 2; for (int j = pos; j >= 1; j--) { if (j + p[j] - 2 >= pos) { int pre = (j - (pos - j)) / 2 - 1; if (pre == 0) { dp[i] = 1; } else { dp[i] = min(dp[pre - 1] + 1, dp[i]); } } } } printf("%d\n", dp[len1 - 1]); }}
转载地址:https://blog.csdn.net/weixin_43820352/article/details/108277580 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月06日 12时49分58秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【Leetcode刷题篇】leetcode79 单词搜索
2019-04-26
【Leetcode刷题篇】leetcode300 最长上升子序列
2019-04-26
【Leetcode刷题篇】leetcode394 字符串解码
2019-04-26
【Leetcode刷题篇】leetcode152 乘积最大数组
2019-04-26
【Leetcode刷题篇】leetcode56 合并区间
2019-04-26
【Leetcode刷题篇】leetcode210 课程表II
2019-04-26
【Leetcode刷题篇】leetcode207 课程表
2019-04-26
【Leetcode刷题篇】leetcode322 零钱兑换
2019-04-26
【Leetcode刷题篇】leetcode437 路径总和III
2019-04-26
【Leetcode刷题篇】leetcode416 分割等和子集
2019-04-26
【Leetcode刷题篇】leetcode31 下一个排列
2019-04-26
【Leetcode刷题篇】leetcode621 任务调度器
2019-04-26
【Leetcode刷题篇/面试篇】通俗易懂详解动态规划-背包问题详解
2019-04-26
【面试篇】HashMap1.7和HashMap1.8的详细区别对比
2019-04-26
【面试篇】ConcurrentHashMap1.8 扩容细节
2019-04-26
【面试篇】ConcurrentHashMap1.7和1.8详解对比
2019-04-26
HashMap的有关知识点大综述
2019-04-26
【面试篇】Java容器面试大集合
2019-04-26
【Linux篇】Linux常用命令之性能优化
2019-04-26
【Leetcode刷题篇】leetcode240 搜索二维矩阵II
2019-04-26