HDU 3336 Count the string(kmp)

来源:互联网 发布:java用户密码加密算法 编辑:程序博客网 时间:2024/06/10 08:15

题目链接:点击打开链接

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

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
14abab
 

Sample Output
6

题目大意:求字串中【前缀+跟前缀相同的子串】的个数,kmp

#include <stdio.h>#include <string.h>char st[210000];int Next[210000];void getNext(char s[],int m){    Next[0] = -1;    int j = 0 , k = -1;    while (j < m)    {        if (k == -1 || s[j] == s[k])        {            ++j;            ++k;            Next[j] = k;        }        else         {            k = Next[k];        }    }}int main(){    int t;    scanf("%d",&t);    while (t-- )    {        memset(Next,0,sizeof(Next));        int n;        scanf("%d %s",&n,st);        getNext(st,n);        int res = Next[n] + n;        for (int j = 0; j < n; j++)          {            if (Next[j] > 0 && Next[j] + 1 != Next[j+1])              {                res += Next[j];            }                        }                    printf("%d\n",res % 10007);    }    return 0;}



0 0