[NOI2014]动物园 【kmp】

题目描述

每次写kmp都要调一万年

这题主要两个数组next[]num[]
num[i]表示以i结尾的前缀所能匹配的数量(可重叠的)

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
const int L=1000010, mod=1000000007;
int n, next[L], num[L], ans;
char s[L];

int main()
{
    cin>>n;
    while(n--) {ans=1;
        char c=getchar(); while(c < 'a' || c > 'z') c=getchar();
        int cnt=0; while(c >= 'a' && c <= 'z') s[++cnt]=c, c=getchar();
        memset(next, 0, sizeof(next)); memset(num, 0, sizeof(num));
        num[1]=1;
        for(int i=2, j=0; i<= cnt; i++){
            while(j && s[i] != s[j+1]) j=next[j];
            if(s[i] == s[j+1]) j++; next[i]=j; num[i]=num[j]+1;
            //printf("%d %d
", next[i], num[i]);
        } 
        for(int i=2, j=0; i <= cnt; i++)
        {
            while(j && s[i] != s[j+1]) j=next[j]; if(s[i] == s[j+1]) ++j;
            while(j*2 > i) j=next[j]; ans=((long long)ans*(num[j]+1))%mod;
        }
        printf("%d
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zerolt/p/9260879.html