hdu3336

http://acm.hdu.edu.cn/showproblem.php?pid=3336

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int next[200005];
char str[200005];
void get_next(char *str,int n)
{
    int i,j;
    next[0]=-1;
    i=0;j=-1;
    while(i<n)
    {
        if(j==-1||str[i]==str[j])
            i++,j++,next[i]=j;
        else
            j=next[j];
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        scanf("%s",str);
        get_next(str,n);
        int i,s=0;
        for(i=1;i<=n;i++)
        {
            if(next[i]!=0)  //next[i]表示前缀等于后缀的最大长度,需仔细理解kmp算法
                s++;
            if(s>10007)
                s=s%10007;
        }
        s=s+n;
        s=s%10007;
        printf("%d\n",s);
    }
    return 0;
}


你可能感兴趣的:(hdu3336)