牛客Manacher专题~回文串
回文串
https://ac.nowcoder.com/acm/problem/14517
牛客Manacher专题~回文串
题意:求一个最长回文子串
题解:Manacher板子题
传送门
首先,对于manacher算法,我们将字符串用没用出现的字母填充后,可以保证,对于每一个对称中心都会有一个字符和这个中心对应
这样就可以解决例如 abba这种长度为偶数的回文串的对称中心没有字符对应的情况
p数组的定义就是以该点为在回文串中回文串最长的长度
取一个maxji'k
/** * ┏┓ ┏┓ * ┏┛┗━━━━━━━┛┗━━━┓ * ┃ ┃ * ┃ ━ ┃ * ┃ > < ┃ * ┃ ┃ * ┃... ⌒ ... ┃ * ┃ ┃ * ┗━┓ ┏━┛ * ┃ ┃ Code is far away from bug with the animal protecting * ┃ ┃ 神兽保佑,代码无bug * ┃ ┃ * ┃ ┃ * ┃ ┃ * ┃ ┃ * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ */ // warm heart, wagging tail,and a smile just for you! // // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // .' \| |// `. // / \||| : |||// \ // / _||||| -:- |||||- \ // | | \ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // 佛祖保佑 永无BUG #include <set> #include <map> #include <stack> #include <cmath> #include <queue> #include <cstdio> #include <string> #include <vector> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; typedef pair<int, int> pii; typedef unsigned long long uLL; #define ls rt<<1 #define rs rt<<1|1 #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define bug printf("*********\n") #define FIN freopen("input.txt","r",stdin); #define FON freopen("output.txt","w+",stdout); #define IO ios::sync_with_stdio(false),cin.tie(0) #define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]\n" #define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]\n" #define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]\n" const int maxn = 3e5 + 5; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const double Pi = acos(-1); LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } LL lcm(LL a, LL b) { return a / gcd(a, b) * b; } double dpow(double a, LL b) { double ans = 1.0; while(b) { if(b % 2)ans = ans * a; a = a * a; b /= 2; } return ans; } LL quick_pow(LL x, LL y) { LL ans = 1; while(y) { if(y & 1) { ans = ans * x % mod; } x = x * x % mod; y >>= 1; } return ans; } char str[maxn], s[maxn << 1]; int len, newlen, p[maxn << 1]; void change() { newlen = len << 1; for(int i = 0; i <= newlen + 1; i++) s[i] = '#'; for(int i = 1; i <= len; i++) s[i << 1] = str[i]; s[newlen + 2] = 0; } void manacher() { change(); int mx = 0, id = 0; for(int i = 1; i <= newlen; i++) { if(mx > i) p[i] = min(p[id * 2 - i], mx - i); else p[i] = 1; while(i - p[i] >= 0 && s[i - p[i]] == s[i + p[i]]) p[i]++; if(i + p[i] > mx) { mx = i + p[i]; id = i; } } } int main() { #ifndef ONLINE_JUDGE FIN #endif while(scanf("%s", str + 1) != EOF) { len = strlen(str + 1); manacher(); int ans = 1; for(int i = 1; i <= newlen; i++) { ans = max(ans, p[i]); } printf("%d\n", ans - 1); } return 0; }