hdu3336 Count the string

Problem Description
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
 

Author
foreverlin@HNU
 

Source
HDOJ Monthly Contest – 2010.03.06



这题是KMP的变形题,主要是了解next数组的用法。

题意是,给一串字符串,问这串字符串所有的前缀总共在这个字符串中出现了几次。

已经有了next数组,next[i]=j表示最大的j使得0~j==i-j~i,因此,对于样例abab,则有

       0   1   2   3

b[]  a    b   a   b

p[]  -1  -1  0   1

对于4个前缀:

a

ab

aba

abab

设dp[i]表示子串b[0~i]共含有以b[i]为结尾的前缀的数目,则以b[i]结尾的前缀数就是自己本身加上以b[p[i]]结尾的前缀数,也就是例如i=2

则有:

a

aba这两个前缀,其中a就是b[p[i]]结尾的前缀。


附代码:

#include 

#define MOD 10007

char b[200005];
int dp[200005];
int p[200005];
int n;

int Pre()
{
    int s,i,j;
    dp[0]=1;
    j=-1;
    p[0]=-1;
    s=1;
    for (i=1;i=0 && b[j+1]!=b[i]) j=p[j];
        if (b[j+1]==b[i]) j++;
        if (j>=0) dp[i]=(dp[j]+1)%MOD;
        else dp[i]=1;
        p[i]=j;
        s=(s+dp[i])%MOD;
    }
    return s;
}

int main()
{
    int i,j,T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        scanf("%s",b);
        printf("%d\n",Pre());
    }
    return 0;
}


你可能感兴趣的:(hdu3336 Count the string)