参考:https://www.cnblogs.com/grandyang/p/4475985.html#undefined
模板:
const int N = 1e5 + ;
int p[N];
string manacher(string s) {
string t = "$#";
for (int i = ; i < s.size(); ++i) {
t += s[i];
t += '#';
}
int mx = , id = , resl = , resc = ;
for (int i = ; i < t.size(); ++i) {
p[i] = mx > i ? min(p[*id-i], mx-i) : ;
while(i+p[i] < t.size() && i-p[i] >= 0 && t[i+p[i]] == t[i-p[i]]) ++p[i];
if(mx < i+p[i]) mx = i+p[i], id = i;
if(resl < p[i]) resl = p[i], resc = i;
}
return s.substr((resc - resl)/, resl-);
}
代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#include<bits/stdc++.h>
using namespace std;
#define y1 y11
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
//#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pli pair<LL, int>
#define pii pair<int, int>
#define piii pair<pii, int>
#define pdd pair<double, double>
#define mem(a, b) memset(a, b, sizeof(a))
#define debug(x) cerr << #x << " = " << x << "\n";
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
//head const int N = 3e5 + ;
int p[N];
int manacher(string s) {
string t = "$#";
for (int i = ; i < s.size(); ++i) {
t += s[i];
t += '#';
}
int mx = , id = , resl = , resc = ;
for (int i = ; i < t.size(); ++i) {
p[i] = mx > i ? min(p[*id-i], mx-i) : ;
while(t[i+p[i]] == t[i-p[i]]) ++p[i];
if(mx < i+p[i]) mx = i+p[i], id = i;
if(resl < p[i]) resl = p[i], resc = i;
}
return resl-;
}
int main() {
string s;
while(cin >> s) {
cout << manacher(s) << endl;
}
return ;
}