[BZOJ3670][Noi2014]动物园:KMP

分析:

可以发现num数组是next数组迭代的层数,为了保证前后缀没有重合部分要再扫一遍字符串。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXLEN=1000005;
const LL MOD=1e9+7;
int n,len,nxt[MAXLEN],cnt[MAXLEN];
char s[MAXLEN];
int main(){
    scanf("%d",&n);
    while(n--){
        scanf("\n%s",s+1);
        len=strlen(s+1);
        nxt[1]=0,cnt[1]=1;LL ans=1;
        for(int i=2,j=0;i<=len;i++){
            while(j&&s[i]!=s[j+1]) j=nxt[j];
            if(s[i]==s[j+1]){
                nxt[i]=++j;
                cnt[i]=cnt[j]+1;
            }
            else nxt[i]=0,cnt[i]=1;
        }
        for(int i=2,j=0;i<=len;i++){
            while(j&&s[i]!=s[j+1]) j=nxt[j];
            if(s[i]==s[j+1]) j++;
            while(j>(i>>1)) j=nxt[j];
            ans=ans*(cnt[j]+1)%MOD;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/ErkkiErkko/p/9509659.html