BZOJ4755:[JSOI2016]扭动的回文串
浅谈\(Manacher\):https://www.cnblogs.com/AKMer/p/10431603.html
题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=4755
用二分加\(hash\)判断是否能在原串已有的回文串上加更多的长度即可。
时间复杂度:\(O(nlogn)\)
空间复杂度:\(O(n)\)
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
const int maxn=2e5+5,P=131;
int n,ans;
int p[maxn];
char a[maxn],b[maxn];
ull ha[maxn],hb[maxn],bin[maxn];
int read() {
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
return x*f;
}
bool check(int l,int r,int L,int R) {
if(l<1||L<1||r>n||R>n)return 0;
return ha[r]-ha[l-1]*bin[r-l+1]==hb[L]-hb[R+1]*bin[R-L+1];
}
void solve(char *s) {
int id=0,mx=0;
for(int i=1;i<=n;i++) {
p[i]=i<=mx?min(mx-i+1,p[(id<<1)-i]):1;
while(s[i-p[i]]==s[i+p[i]])p[i]++;
if(i+p[i]-1>mx)mx=i+p[i]-1,id=i;
int L=i-p[i]+1,R=i+p[i]-1;
if(s==a)L--,R--;else L++,R++;
int l=0,r=n;
while(l<r) {
int mid=(l+r+1)>>1;
if(check(L-mid+1,L,R,R+mid-1))l=mid;
else r=mid-1;
}
ans=max(ans,p[i]-1+l);
}
}
int main() {
n=read(),bin[0]=1;
scanf("%s%s",a+1,b+1);
for(int i=n;i;i--) {
a[i<<1]=a[i],b[i<<1]=b[i];
a[(i<<1)-1]=b[(i<<1)-1]='#';
}
a[0]=b[0]='$',a[n<<1|1]=b[n<<1|1]='#',n=n<<1|1;
for(int i=1;i<=n;i++)bin[i]=bin[i-1]*P;
for(int i=1;i<=n;i++)ha[i]=ha[i-1]*P+a[i];
for(int i=n;i;i--)hb[i]=hb[i+1]*P+b[i];
solve(a),solve(b),printf("%d\n",ans);
return 0;
}