A Horrible Poem(bzoj 2795)

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
/*
  挑了半天,原来是hash判断写错了,无语。
  首先我们可以知道,一个长度为len的子串,它的循环节一定是len的约数,所以只要找len的约数,再用hash判断就行了。但是这样的复杂度是q√n的,会TLE,所以考虑优化。
  考虑如果有一个字母出现了k次,那么这个子串的循环节个数一定是k的约数,我们把所有的k取一个gcd,再找约数。 
*/
#include<cstdio>
#include<iostream>
#include<algorithm>
#define P 31
#define N 500010
#define lon long long
using namespace std;
int cnt[N][26],n,m,ans;
char s[N];
lon hash[N],base[N];
void get_hash(){
    base[0]=1;
    for(int i=1;i<=n;i++){
        hash[i]=hash[i-1]*P+s[i]-'a';
        base[i]=base[i-1]*P;
    }
}
void check(int x,int y,int t){
    lon has1=hash[y-t]-hash[x-1]*base[y-x+1-t];
    lon has2=hash[y]-hash[x+t-1]*base[y-x+1-t];
    if(has1==has2)ans=min(ans,t);
}
int main(){
    scanf("%d%s%d",&n,s+1,&m);
    get_hash();
    for(int j=0;j<=25;j++)
        for(int i=1;i<=n;i++)
            cnt[i][j]=cnt[i-1][j]+(s[i]-'a'==j);
    for(int i=1;i<=m;i++){
        ans=N;
        int x,y,vgcd;scanf("%d%d",&x,&y);
        vgcd=y-x+1;
        for(int j=0;j<=25;j++)
            vgcd=__gcd(vgcd,cnt[y][j]-cnt[x-1][j]);
        for(int j=1;j*j<=vgcd;j++){
            if(vgcd%j)continue;
            check(x,y,(y-x+1)/j);
            check(x,y,(y-x+1)/(vgcd/j));
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2017-01-03 14:41  karles~  阅读(697)  评论(1编辑  收藏  举报