HDU 3064 最长回文 manacher算法模板

来源:互联网 发布:网络订票如何取票 编辑:程序博客网 时间:2024/06/07 06:36

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3068

题意:

Problem Description
给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
回文就是正反读都是一样的字符串,如aba, abba等
 

Input
输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000
 

Output
每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.

思路:就是一个裸的manacher算法题,留个模板

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <queue>#include <map>using namespace std;const int N = 200010;char s[N], str[N*2];int p[N*2];int manacher(){    int i;    for(i = 1; s[i]; i++)        str[i*2] = s[i], str[i*2+1] = '#';    str[0] = '?', str[1] = '#', str[i*2] = '\0';    int res = 0, k = 0, maxk = 0;    for(int i = 2; str[i]; i++)    {        p[i] = i < maxk ? min(maxk - i, p[2*k-i]) : 1;        while(str[i-p[i]] == str[i+p[i]]) p[i]++;        if(p[i] + i > maxk)            k = i, maxk = i + p[i];        res = max(res, p[i]);    }    return res - 1;}int main(){    while(~ scanf(" %s", s + 1))        printf("%d\n", manacher());    return 0;}



0 0