BZOJ-2795 [Poi2012]A Horrible Poem(hash+线性筛)
题目描述
给出一个由小写英文字母组成的字符串 \(S(1\leq |S|\leq 5\times 10^5)\),再给出 \(q(1\leq q\leq 2\times 10^6)\) 个询问,要求回答 \(S\) 某个子串的最短循环节。如果字符串 \(B\) 是字符串 \(A\) 的循环节,那么 \(A\) 可以由 \(B\) 重复若干次得到。
分析
\(1.\) 循环节的长度肯定是串长的因子。
\(2.\) 当 \(str[l\cdots r-len]=str[l+len\cdots r]\) 时,\(str[l\cdots l+len-1]\) 必为 \(str[l\cdots r]\) 的循环节。
根据这两条性质,枚举 \(len=r-l+1\) 的因子,用 \(\text{hash}\) 判断,首先线性筛预处理质数,\(vis[i]\) 记录数字 \(i\) 的最小质因数。找 \(len\) 的最短循环节的时候用递归的思想,继续找 \(len/vis[len]\) 的最短循环节。
代码
#include <bits/stdc++.h>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
const int BASE1=131;
const int BASE2=139;
const int N=2e6+10;
int n,q;
char str[N+10];
unsigned long long pow1[N+10],pow2[N+10];
unsigned long long hash1[N+10],hash2[N+10];
bool check(int op,int l,int r,int len)//判断[l,r]区间长度为len的子区间是否为循环节,与比较[l,r-len]和[l+len,r]这两段的hash值是等价的
{
if(op==1)
return hash1[r-len]-hash1[l-1]*pow1[r-l+1-len]==hash1[r]-hash1[l+len-1]*pow1[r-l+1-len];
if(op==2)
return hash2[r-len]-hash2[l-1]*pow2[r-l+1-len]==hash2[r]-hash2[l+len-1]*pow2[r-l+1-len];;
}
int vis[N+10],prime[N+10],d[N],cnt;
void init()
{
for(int i=2;i<=N;i++)
{
if(!vis[i])
{
vis[i]=i;
prime[++cnt]=i;
}
for(int j=1;i*prime[j]<=N&&j<=cnt;j++)
{
vis[i*prime[j]]=prime[j];
if(i%prime[j]==0)
break;
}
}
}
int main()
{
init();
cin>>n;
scanf("%s",str+1);
pow1[0]=pow2[0]=1;
for(int i=1;i<=n;i++)
{
pow1[i]=pow1[i-1]*BASE1;
pow2[i]=pow2[i-1]*BASE2;
}
for(int i=1;i<=n;i++)
{
hash1[i]=hash1[i-1]*BASE1+str[i];
hash2[i]=hash2[i-1]*BASE2+str[i];
}
cin>>q;
while(q--)
{
int l=read(),r=read();
int len=r-l+1,tot=0;
while(len!=1)
{
d[++tot]=vis[len];
len=len/vis[len];
}
int ans=r-l+1;
for(int i=1;i<=tot;i++)
if(check(1,l,r,ans/d[i])&&check(2,l,r,ans/d[i]))
ans=ans/d[i];
printf("%d\n",ans);
}
return 0;
}
posted on 2020-11-18 12:13 DestinHistoire 阅读(136) 评论(0) 收藏 举报
浙公网安备 33010602011771号