备战NOIP——模板复习25

这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。

Manacher算法

/*Copyright: Copyright (c) 2018
*Created on 2018-11-08
*Author: 十甫
*Version 1.0 
*Title: Manacher
*Time: inf mins
*/
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
const int maxn = 51000100;
using namespace std;

int n, pal[maxn], ans;
char origin[maxn], data[maxn<<1];
void manacher() {
    int maxright = 0, mid = 0;
    for(int i = 1;i < n;i++) {
        if(i < maxright) {
            pal[i] = min(pal[(mid << 1) - i], pal[mid] + mid - i);
        } else {
            pal[i] = 1;
        }
        for(;data[i + pal[i]] == data[i - pal[i]];++pal[i]);
        if(pal[i] + i > maxright) {
            maxright = pal[i] + i;
            mid = i;
        }
    }
}
void turn() {
    data[0] = data[1] = 11;
    for(int i = 0;i < n;i++) {
        data[i * 2 + 2] = origin[i];
        data[i * 2 + 3] = 11;
    }
    n = n * 2 + 2;
    data[n] = 0;
}
int main() {
    scanf("%s", origin);
    n = strlen(origin);
    turn();
    manacher();
    ans = 1;
    for(int i = 0;i < n;i++) {
        ans = max(ans, pal[i]);
    }
    printf("%d\n", ans - 1);
    return 0; 
}

 

posted @ 2018-11-08 13:57  十甫  阅读(99)  评论(0编辑  收藏  举报