哈希
我会O(nq)!
假如字符串 s s 的循环节长度为,那么 len l e n 的倍数也一定是 s s 的循环节。那么我们可以假定当前的最短循环节为,然后类似质因数分解一样不断缩就好了。
具体见代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 500005
#define F inline
using namespace std;
typedef unsigned long long ull;
int n,q,p[N],a[N]; char s[N];
ull h[N],pw[N]; bool f[N];
F char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
return l==r?EOF:*l++;
}
F int _read(){
int x=0; char ch=readc();
while (!isdigit(ch)) ch=readc();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x;
}
F void Make(){
for (int i=2;i<=n;i++){
if (!f[i]) p[++p[0]]=i,a[i]=i;
for (int j=1;j<=p[0]&&p[j]*i<=n;j++){
f[p[j]*i]=true,a[p[j]*i]=p[j];
if (i%p[j]==0) break;
}
}
}
F ull calc(int l,int r){ return h[r]-h[l-1]*pw[r-l+1]; }
int main(){
scanf("%d%s",&n,s+1),Make(),pw[0]=1;
for (int i=1;i<=n;i++)
h[i]=h[i-1]*29+s[i],pw[i]=pw[i-1]*29;
for (q=_read();q;q--){
int l=_read(),r=_read(),len=r-l+1,ans=len;
while (len!=1){
int x=a[len];
while (ans%x==0&&calc(l,r-ans/x)==calc(l+ans/x,r)) ans/=x;
while (len%x==0) len/=x;
}
printf("%d\n",ans);
}
return 0;
}