BZOJ2795 [Poi2012]A Horrible Poem(洛谷P3538)

292 篇文章 1 订阅
281 篇文章 1 订阅

哈希

BZOJ题目传送门
洛谷题目传送门

我会O(nq)!

假如字符串 s s 的循环节长度为len,那么 len l e n 的倍数也一定是 s s 的循环节。那么我们可以假定当前的最短循环节为len(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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值