P3538 [POI2012]OKR-A Horrible Poem(题解)

· · 题解

P3538 [POI2012]OKR-A Horrible Poem 解题报告

这题还是挺有意思的。

字符串Hash板子题。

学到了三个小 tips:

  1. 判断一个字符串是否存在长度为 len 的循环节不需要暴力枚举,复杂度为 O(\frac{n}{len}),可以直接判断 [l,r-len] 是否等于 [l+len,r] 复杂度 O(1)。
  2. 如果一个字符串具有长度为 x 的循环节,对任意的 x\ |\ y 且 y\ |\ (r-l+1) 肯定有 y 也是循环节,所以可以直接枚举每个质因数是否除掉。
  3. 对于多组询问值域 \le10^6 分解质因数问题,我们不需要 O(Q\sqrt{n}) 地暴力,我们可以 O(n)+O(\log n) 地用线性筛筛出一个数最大的质因子。

就这样。

代码如下


//愿你和你重要的人能够再次重逢!
#include<bits/stdc++.h>
using namespace std;
template<typename T>inline void read(T &x)
{
    x=0;char c=getchar(),f=0;
    for(;c<'0'||c>'9';c=getchar()) if(!(c^45)) f=1;
    for(;c>='0'&&c<='9';c=getchar()) x=(x<<1)+(x<<3)+(c^48);
    if(f) x=-x;
}
const int B=137;unsigned bas[500005],has[500005];
int n,Q,pc,p[500005],mx[500005],st[500005],tp;char v[500005],c[500005];
inline unsigned Hash(int l,int r) {return has[r]-bas[r-l+1]*has[l-1];}
int main()
{
    read(n),scanf("%s",c+1);
    for(int i=2;i<=n;i++)
    {
        if(!v[i]) p[++pc]=i,mx[i]=i;
        for(int j=1;j<=pc&&i*p[j]<=n;j++) {v[i*p[j]]=1,mx[i*p[j]]=p[j];if(!(i%p[j])) break;}
    }
    bas[0]=1;for(int i=1;i<=n;i++) bas[i]=bas[i-1]*B,has[i]=has[i-1]*B+c[i]-'a'+1;
    for(read(Q);Q--;)
    {
        int l,r,len;read(l),read(r),len=r-l+1,tp=0;
        while(len^1) st[++tp]=mx[len],len/=mx[len];
        len=r-l+1;for(int i=1,qwq;i<=tp;i++) {qwq=len/st[i];if(Hash(l,r-qwq)==Hash(l+qwq,r)) len/=st[i];}
        printf("%d\n",len);
    }
    return 0;
}
###### ```