P10915 [蓝桥杯 2024 国 B] 最长回文前后缀
P10915 [蓝桥杯 2024 国 B] 最长回文前后缀
首先可以发现,整个串的最长回文前后缀肯定得保留,所以我们先把原串最长回文前后缀加进答案,然后去掉,再考虑剩下的部分。
那这样,新串的头尾一定是不匹配的,要想让答案更大只能删前缀或者后缀。
我们的目标肯定是让新串的最长回文前后缀最大,那就维护每个前缀、后缀的最长回文前后缀,取个 \(\max\) 就行了。
现在的问题就成了求最长回文前后缀,这也不难,直接搞正反哈希+二分就行了。
#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
const int N=5e5+10;
ull h1[N], h2[N], p[N];
int f[N];
string s, t;
int n, m, ans;
ull Hash1(int l, int r){
return h1[r]-h1[l-1]*p[r-l+1];
}
ull Hash2(int l, int r){
return h2[r]-h2[l-1]*p[r-l+1];
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
cin>>s;
s=" "+s;
int len=(int)s.size()-1;
int now=1;
while(now<len-now+1 && s[now]==s[len-now+1]) now++;
int x=now, y=len-now+1;
if(s[now]!=s[len-now+1] || now==len-now+1) now--;
s=s.substr(x, y-x+1);
s=" "+s;
n=(int)s.size()-1;
t=" ";
for(int i=n; i; i--) t+=s[i];
p[0]=1;
for(int i=1; i<=n; i++) p[i]=p[i-1]*131;
for(int i=1; i<=n; i++){
h1[i]=h1[i-1]*131+s[i];
h2[i]=h2[i-1]*131+t[i];
}
for(int i=1; i<=n; i++){
int l=0, r=i;
while(l<r){
int mid=(l+r+1)>>1;
ull hl=Hash1(1, mid), hr=Hash2(n-i+1, n-(i-mid+1)+1);
if(mid<i-mid+1 && hl==hr) l=mid;
else r=mid-1;
}
f[i]=l;
}
for(int i=1; i<=n; i++) ans=max(ans, f[i]);
fill(f, f+n+1, 0);
for(int i=1; i<=n; i++){
int l=0, r=i;
while(l<r){
int mid=(l+r+1)>>1;
ull hl=Hash2(1, mid), hr=Hash1(n-i+1, n-(i-mid+1)+1);
if(mid<i-mid+1 && hl==hr) l=mid;
else r=mid-1;
}
f[i]=l;
}
for(int i=1; i<=n; i++) ans=max(ans, f[i]);
cout<<ans+now;
return 0;
}

浙公网安备 33010602011771号