hdu 3336 Count the string(next数组)

题意:统计前缀在串中出现的次数

思路:next数组,递推

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

#define MaxSize 200005
#define Mod 10007

char str[MaxSize];
int _next[MaxSize];
int dp[MaxSize];
int len;

void GetNext(char t[]){//求next数组
    int j,k;//,len;
    j=0;
    k=-1;
    _next[0]=-1;
    //len=strlen(t);
    while(j<len){
        if(k==-1||t[j]==t[k]){
            ++j;
            ++k;
            _next[j]=k;//此句可由优化替代
            /*优化(仅保证求KMPIndex时可用。谨慎使用。)
            if(t[j]!=t[k])next[j]=k;
            else next[j]=next[k];
            */
        }
        else k=_next[k];
    }
}

int main(){
    int t,i,ans;
    scanf("%d",&t);
    while(t--){
        scanf("%d%s",&len,str);
        GetNext(str);//求子串的next数组
        dp[0]=0;
        ans=0;
        for(i=1;i<=len;++i){
            dp[i]=dp[_next[i]]+1;
            dp[i]%=Mod;
            ans+=dp[i];
            ans%=Mod;
        }
        printf("%d\n",ans);
    }
    return 0;
}
View Code

 

posted @ 2015-08-21 20:50  gongpixin  阅读(189)  评论(0编辑  收藏  举报