L2-008 manacher 的应用

  附上题目链接:https://www.patest.cn/contests/gplt/L2-008

  

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

 

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int maxn = 3*1000 + 100;
char s[maxn];
char a[maxn];
int p[maxn];

void manacher(char *s) {
    int len = strlen(s+1);
    int m = 2*len + 1;
    for(int i=1; i<=len; i++) {
        a[i<<1] = s[i];
        a[i<<1|1] = '#';
    }
    a[0] = '+'; a[1] = '#'; a[m+1] = '-';
    int mx = 0, idx;
    for(int i=1; i<=m; i++) {
        if(mx > i) p[i] = min(p[2*idx-i], mx-i);
        else p[i] = 1;
        for(; a[i-p[i]]==a[i+p[i]]; p[i]++);
        if(p[i]+i>mx) mx=p[i]+i, idx = i;
    }
}

int main() {
    gets(s+1);
    manacher(s);
    int res = 0;
    int len = strlen(s+1);
    for(int i=1; i<=2*len+1; i++) {
        res = max(res, p[i]);
    }
    printf("%d\n", res-1);
    return 0;
}

 

posted @ 2016-06-03 23:03  xing-xing  阅读(218)  评论(0编辑  收藏  举报