A Horrible Poem
哈希加质因数分解求子串最短循环节
正文
// 原题:https://oj.yecheng.tv/p/T1460
// 题意:给长 n 的串 S 与 q 个询问 [a,b],输出子串 S[a..b] 的最短循环节长度。
// 思路:预处理滚动哈希 O(1) 判两段相等;对每个询问把长度质因数分解,从 ans=len 起对每个质因子尝试除下去并用哈希验证周期性。
// 复杂度:O(n+q·log n) 时间 / O(n) 空间
// 易错点:判周期是比较 S[l..r-d] 与 S[l+d..r] 两段,d 必须严格小于子串长度;q 达 2e6 必须关同步并直接输出。
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull BS=911382323ull;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if(!(cin>>n)) return 0;
string s;
if(!(cin>>s)) return 0;
vector<ull> h(n+1,0),pw(n+1,1);
for(int i=0;i<n;i++){
h[i+1]=h[i]*BS+(ull)(unsigned char)s[i];
pw[i+1]=pw[i]*BS;
}
auto seg=[&](int l,int r)->ull{
if(l>r) return 0ull;
return h[r+1]-h[l]*pw[r-l+1];
};
int lim=(int)sqrt((double)n)+2;
vector<int> primes;
vector<int> comp(lim+1,0);
for(int i=2;i<=lim;i++){
if(!comp[i]) primes.push_back(i);
for(int p:primes){
long long v=1LL*i*p;
if(v>lim) break;
comp[(int)v]=1;
if(i%p==0) break;
}
}
int q;
if(!(cin>>q)) return 0;
while(q--){
int a,b;
cin>>a>>b;
int l=a-1,r=b-1;
int len=r-l+1;
int ans=len;
int x=len;
for(int p:primes){
if(1LL*p*p>x) break;
if(x%p==0){
while(x%p==0){
if(ans%p==0&&seg(l,r-ans/p)==seg(l+ans/p,r)) ans/=p;
x/=p;
}
}
}
if(x>1){
if(ans%x==0&&seg(l,r-ans/x)==seg(l+ans/x,r)) ans/=x;
}
cout<<ans<<'\n';
}
return 0;
}
一本通·提高篇的其它内容
- 活动安排
- 种树
- 喷水装置
- 加工生产调度
- 智力大冲浪
- 数列极差
- 数列分段
- 线段
- 家庭作业
- 钓鱼
- 糖果传递
- 愤怒的牛
- Best Cow Fences
- 曲线
- 数列分段 II
- 扩散
- 灯泡
- 传送带
- 数的划分
- 生日蛋糕
- 小木棍
- Addition Chains
- 埃及分数
- 平板涂色
- 质数方阵
- 靶形数独
- 电路维修
- 魔板
- Knight Moves
- 棋盘游戏
- Keyboarding
- 移动玩具
- 山峰和山谷
- Oulipo
- 图书管理
- Power Strings
- Seekthe Name, Seek the Fame
- Friends
- Beads
- Antisymmetry
- 门票
- 收集雪花
- 剪花布条
- Power Strings
- Radio Transmission
- OKR-Periods of Words
- 似乎在梦中见过的样子
- Censoring
- Phone List
- The XOR Largest Pair
- Nikitosh 和异或
- Immediate Decodability
- L 语言
- Secret Message 秘密信息
- 背单词
- The Xor-longest Path
- Keywords Search
- 玄武密码
- Censoring
- 单词