hdu3336 kmp求一個z字符串(包括本身)所有前綴出現次數的總和。

It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example: 
s: "abab" 
The prefixes are: "a", "ab", "aba", "abab" 
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6. 
The answer may be very large, so output the answer mod 10007. 

Input

The first line is a single integer T, indicating the number of test cases. 
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters. 

Output

For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

Sample Input

1
4
abab

Sample Output

6
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int f[200000+10];
char s[200000+10];
char st[200000+10];
int dp[200000+10];
int cnt;
int  find(char *T,char *P,int *f)
{
    int n=strlen(T);
    int m=strlen(P);
    int j=0;
    int cnt=0;
    for(int i=0;i<n;i++)
    {
        if(j && T[i]!=P[j]) j=f[j];
        if(T[i]==P[j]) j++;
        if(j==m) {cnt++;}

    }
    return cnt;
}
void getFail(char *P,int *f)
{
    int m =strlen(P);
    f[0]=f[1]=0;
    for(int i=1;i<m;i++)
    {
        int j=f[i];
        while(j && P[i]!=P[j]) j=f[j];
        f[i+1] = P[i]==P[j]?j+1:0;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
  
    while(t--)
    {
        cnt=0;
        int n;
        scanf("%d",&n);
        scanf("%s",&s);
        getFail(s,f);
         dp[0]=0;//dp[i]表示每個前綴出現的次數。
        for(int i=1;i<=n;i++)
        {
            dp[i]=dp[f[i]]+1;
            cnt+=dp[i]%10007;
            cnt%=10007;
        }
        printf("%d\n",cnt);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章