Hdu 3068 最长回文(manacher算法)

解析:

这题是manacher算法的模板题。
关于算法的解析请看这个连接:http://blog.csdn.net/ggggiqnypgjg/article/details/6645824/

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110005;
char str[N<<1], s[N];
int p[N<<1];
int manacher() {
    int len = strlen(s);
    for(int i = 0; i < len; i++) {
        str[i*2] = '#';
        str[i*2+1] = s[i];
    }
    str[len*2] = '#';
    str[len*2+1] = '\0';
    len = strlen(str);
    int maxp = 0, id = 0;
    for(int i = 0; i < len; i++) {
        if(maxp > i) p[i] = min(maxp-i, p[id*2-i]); 
        else p[i] = 1;
        for(;str[i-p[i]] == str[i+p[i]] && i+p[i] < len && i-p[i] >= 0; p[i]++);
        if(i+p[i] > maxp) {
            maxp = p[i]+i;
            id = i;
        }
    }
    int maxv = 1;
    for(int i = 0; i < len; i++) {
        maxv = max(maxv, p[i]-1);
    }
    return maxv;
}
int main() {
    //freopen("in.txt", "r", stdin);
    while(scanf("%s", &s) != EOF) {
        printf("%d\n", manacher());
    }
    return 0;
}

你可能感兴趣的:(HDU,Manacher,3068)