首页 技术 正文
技术 2022年11月20日
0 收藏 978 点赞 3,656 浏览 1496 个字

2795: [Poi2012]A Horrible Poem

Time Limit: 50 Sec  Memory Limit: 128 MB
Submit: 484  Solved: 235
[Submit][Status][Discuss]

Description

给出一个由小写英文字母组成的字符串S,再给出q个询问,要求回答S某个子串的最短循环节。
如果字符串B是字符串A的循环节,那么A可以由B重复若干次得到。

Input

第一行一个正整数n (n<=500,000),表示S的长度。
第二行n个小写英文字母,表示字符串S。
第三行一个正整数q (q<=2,000,000),表示询问个数。
下面q行每行两个正整数a,b (1<=a<=b<=n),表示询问字符串S[a..b]的最短循环节长度。

Output

依次输出q行正整数,第i行的正整数对应第i个询问的答案。

Sample Input

8
aaabcabc
3
1 3
3 8
4 8

Sample Output

1
3
5

HINT

 

Source

鸣谢 jiangzoi&oimaster

2795: [Poi2012]A Horrible Poem

2795: [Poi2012]A Horrible Poem

首先我们可以知道,一个长度为len的子串,它的循环节一定是len的约数,所以只要找len的约数,再用hash判断就行了。但是这样的复杂度是q√n的,会TLE,所以考虑优化。
考虑如果有一个字母出现了k次,那么这个子串的循环节个数一定是k的约数,我们把所有的k取一个gcd,再找约数。

#include<cstdio>
#include<algorithm>
#include<iostream>
#define P 31
#define R register
#define ull unsigned long long
using namespace std;
int read(){
R int x=;bool f=;
R char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return f?x:-x;
}
const int N=5e5+;
ull hash[N],base[N];
int n,m,vgcd,ans,c[N][];;
char s[N];
void get_hash(){
base[]=;
for(int i=;i<=n;i++){
hash[i]=hash[i-]*P+s[i]-'a';
base[i]=base[i-]*P;
}
}
void check(int x,int y,int t){
ull has1=hash[y-t]-hash[x-]*base[y-x+-t];
ull has2=hash[y]-hash[x+t-]*base[y-x+-t];
if(has1==has2) ans=min(ans,t);
}
int main(){
n=read();gets(s+);m=read();
get_hash();
for(int i=;i<=;i++){
for(int j=;j<=n;j++){
c[j][i]=c[j-][i]+(s[j]-'a'==i);
}
}
for(int i=,x,y;i<=m;i++){
x=read();y=read();ans=N;vgcd=y-x+;
for(int j=;j<=;j++) vgcd=__gcd(vgcd,c[y][j]-c[x-][j]);
for(int j=;j*j<=vgcd;j++){
if(vgcd%j) continue;
check(x,y,(y-x+)/j);
check(x,y,(y-x+)/(vgcd/j));
}
printf("%d\n",ans);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,361
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,853