省选NOI-专题[字符串][hash][数论]:P3538 [POI2012]OKR-A Horrible Poem
我这里推荐一下我的博客
在博客里观看更美观哦~
题目
华丽的分割线
解析
判断循环节
设在
如图所示:
当两个串相错开
两个子串完全相同,则结论成立,用
数学
既然知道可以
不行,因为答案不满足单调性,而枚举又变为
我们可以有技巧的枚举,设区间长度
那么
这样可以用
假设两份可以,那么
知道最后
因为在满足循环节定义的前提下,尽可能多除以因数,故答案最小
但仍然超时,可以之前预处理
复杂度
由于之前预处理哈希值和素数,所以复杂度
共有
因为
前者需枚举
所以复杂度为
所以总复杂度为
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
const int N=600000;
void read(int &x)
{
char c;
c=getchar();
int f;
f=1;
x=0;
while((c<'0'||c>'9')&&c!='-')
{
c=getchar();
}
if(c=='-')
{
f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=(x<<3)+(x<<1)+(c^48);
c=getchar();
}
x=x*f;
}
char a[N];
ll hash1[N],pow1[N];
ll p1=998244353;
ll check1(int x,int y)
{
return ((hash1[y]-hash1[x-1]*pow1[y-x+1]%p1)+p1)%p1;
}
int prime[N],tot;
bool is_prime[N];
void getprime(int n)
{
int i,j;
is_prime[1]=1;
for(i=2;i<=n;i++)
{
if(is_prime[i]==0)
{
tot++;
prime[tot]=i;
}
for(j=1;j<=tot&&i*prime[j]<=n;j++)
{
is_prime[i*prime[j]]=1;
if(i%prime[j]==0)
{
break;
}
}
}
}
int pr[N],ptot;
int main()
{
int i,j,la,n,x,y,len,now;
read(n);
tot=0;
getprime(n);
scanf("%s",a+1);
la=strlen(a+1);
pow1[0]=1;
for(i=1;i<=la;i++)
{
pow1[i]=pow1[i-1]*26%p1;
hash1[i]=(hash1[i-1]*26+a[i]-'a')%p1;
}
read(n);
for(i=1;i<=n;i++)
{
read(x);
read(y);
len=y-x+1;
ptot=0;
int up=sqrt(len);
for(j=1;j<=tot&&prime[j]<=up;j++)
{
if(len%prime[j]==0)
{
ptot++;
pr[ptot]=prime[j];
}
while(len%prime[j]==0)
{
len/=prime[j];
}
}
if(len!=1)
{
ptot++;
pr[ptot]=len;
}
len=y-x+1;
for(j=1;j<=ptot;j++)
{
now=len/pr[j];
while(check1(x,y-now)==check1(x+now,y))
{
len/=pr[j];
if(len%pr[j]!=0)
{
break;
}
now=len/pr[j];
}
}
printf("%d\n",len);
}
}