【bzoj3670】 [Noi2014]动物园

首先显然要用KMP把next先求出来
那么我们再考虑求一个cnt数组:表示可重叠的既是前缀又是后缀的子串个数
这个可以用递推求:cnt[x]=cnt[next[x]]+1,想想就明白了
那num又如何得到呢
num与cnt的区别就是不能重叠,也就是那个子串的长度不能超过原串的一半
那么从一个位置x一直往前跳next,跳到第一个小于等于x的一半的地方,记为pre[x],那么有num[x]=cnt[pre[x]]+1
显而易见吧
但是如果暴力跳next的话复杂度就不对了 不过我们注意到有这样的一个关系:pre[next[x]]<=pre[x]

利用这个单调性从后往前跳就可以了

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long lol;
int gi(){
    int res=0,fh=1;char ch=getchar();
    while((ch>'9'||ch<'0')&&ch!='-')ch=getchar();
    if(ch=='-')fh=-1,ch=getchar();
    while(ch>='0'&&ch<='9')res=res*10+ch-'0',ch=getchar();
    return fh*res;
}
const int MAXN=1000010;
const int INF=1e9;
const int MOD=1e9+7;
char s[MAXN];
int next[MAXN],cnt[MAXN],num[MAXN],pre[MAXN];
bool vis[MAXN];
int main(){
    int T=gi();
    while(T--){
        scanf("%s",s+1);
        next[0]=next[1]=0;
        int l=strlen(s+1);
        for(int i=1;i<l;i++){
            int o=next[i];
            while(o&&s[i+1]!=s[o+1])o=next[o];
            next[i+1]=s[i+1]==s[o+1]?o+1:0;
        }
        cnt[0]=-1;
        for(int i=1;i<=l;i++)cnt[i]=cnt[next[i]]+1,vis[i]=0;
        for(int i=l;i;i--){
            if(vis[i])continue;
            int now,last=next[i];
            for(now=i;now;now=next[now]){
                vis[now]=1;
                while((last<<1)>now)last=next[last];
                pre[now]=last;
            }
        }
        lol ans=1;
        for(int i=1;i<=l;i++)ans=ans*(cnt[pre[i]]+2)%MOD;
        printf("%d\n",int(ans));
    }
    return 0;
}

 

posted @ 2016-07-11 16:37  Yangjiyuan  阅读(149)  评论(0编辑  收藏  举报