HDU3068 最长回文(manacher)

来源:互联网 发布:mac wi fi 未安装硬件 编辑:程序博客网 时间:2024/05/12 01:43

题意:最长回文。


思路:manacher算法。可以作模板了。


#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<vector>#include<map>#include<algorithm>using namespace std;typedef long long ll;const int inf = 0x3f3f3f3f;const int mod = 1000000007;const int maxn = 110005;int manacher(char s[], char str[], int p[]){    int len = strlen(s);    str[0] = '*';//第一位是*,最后一位是'\0',防止下面的while越界    for(int i = 0; i <= len; ++i){//初始化        str[i * 2 + 1] = '#';        str[i * 2 + 2] = s[i];    }    len = 2 * len + 1;    int pos = 0, maxlen = 1;    p[0] = 1;    for(int i = 2; i < len; ++i){        if(i < p[pos] + pos){            p[i] = min(pos + p[pos] - i, p[pos * 2 - i]);        } else {            p[i] = 1;        }        while(str[i - p[i]] == str[i + p[i]]){            ++p[i];        }        if(i + p[i] > pos + p[pos]){            pos = i;//更新位置        }        if(p[i] > maxlen){            maxlen = p[i];//更新结果        }    }    return maxlen - 1;}char s[maxn], str[maxn * 2];int p[maxn * 2];int main(){    while(~scanf("%s", s)){        printf("%d\n", manacher(s, str, p));    }    return 0;}