鱼C论坛

 找回密码
 立即注册
查看: 977|回复: 0

[技术交流] PTA A_1040 Longest Symmetric String

[复制链接]
发表于 2020-2-27 19:07:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 798236606 于 2020-8-29 11:18 编辑

传送门:https://pintia.cn/problem-sets/9 ... /994805446102073344

解:
manacher算法
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>

  4. using namespace std;

  5. const int maxn = 1e3 + 10;

  6. char a[maxn];
  7. char b[maxn * 2];
  8. int p[maxn * 2];

  9. int init(char *a)
  10. {

  11.     b[0] = '!';
  12.     b[1] = '#';

  13.     int j = 2;

  14.     for (int i = 0; i < strlen(a); ++i)
  15.     {
  16.         b[j++] = a[i];
  17.         b[j++] = '#';
  18.     }
  19.     b[j] = '\0';

  20.     return j;
  21. }

  22. int manacher(char *a)
  23. {
  24.     int len = init(a);
  25.     int id = -1, mx = 0, ans = -1;

  26.     for (int i = 1; i < len; ++i)
  27.     {
  28.         p[i] = (i < mx) ? min(p[2 * id - i], mx - i) : 1;
  29.    
  30.         while (b[i - p[i]] == b[i + p[i]]) ++p[i];

  31.         if (i + p[i] > mx)
  32.         {
  33.             mx = i + p[i];
  34.             id = i;
  35.         }

  36.         if (p[i] > ans) ans = p[i];
  37.     }

  38.     return ans - 1;
  39. }

  40. int main(void)
  41. {
  42.     // freopen("input.txt", "r", stdin);
  43.     scanf("%[^\n]", a);

  44.     printf("%d", manacher(a));

  45.     return 0;
  46. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-5 16:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表