hdoj3068--最长回文(manacher模板)

题目大意:如题
分析:manacher算法。传送门:http://acm.uestc.edu.cn/bbs/read.php?tid=3258
注意!!!两次循环的条件不要用strlen,直接s[i],否则超时。TLE好几发后,涨姿势了~

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 110055;

char s1[maxn], s2[2*maxn];
int p[2*maxn];

void init() {
    s2[0] = '@', s2[1] = '#';
    for(int i = 0, l = 2; s1[i]; i++, l += 2) {
        s2[l] = s1[i];
        s2[l+1] = '#';
    }
}

int manacher() {
    int ans = 0, mx = 0, id;
    for(int i = 1; s2[i]; i++) {
        if(mx > i) p[i] = min(p[2*id-i], mx-i);
        else  p[i] = 1;
        while(s2[i+p[i]] == s2[i-p[i]]) p[i]++;
        if(p[i]+i > mx) {
            mx = p[i]+i;
            id = i;
        }
        ans = max(ans, p[i]);
    }
    return ans-1;
}

int main() {
    int T = 0;
    while(~scanf("%s", s1)) {
        init();
        printf("%d\n", manacher());
        memset(s1, 0, sizeof(s1));
        memset(s2, 0, sizeof(s2));
    }
    return 0;
}

你可能感兴趣的:(hdoj)