Count the string

来源:互联网 发布:阿里云服务器如何建站 编辑:程序博客网 时间:2024/06/11 02:41

题目描述

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. 

输入描述:

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.       

输出描述:

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

输入

14abab

输出

6
#include <cstdio>#include <cstring>int const MAX = 200000 + 5;int const MOD = 10007;int next[MAX];char s[MAX]; void get_next(){    int i = 0, j = -1;    next[0] = -1;    while(s[i] != '\0')    {        if(j == - 1 || s[i] == s[j])        {            i++;            j++;            next[i] = j;        }        else            j = next[j];    }} int main(){    int T, len, ans;    scanf("%d", &T);    while(T--)    {        memset(next, 0, sizeof(next));        scanf("%d %s", &len, s);        get_next();        ans = len;        for(int i = 1; i <= len; i++)        {            int tmp = next[i];            while(tmp)            {                ans = (ans + 1) % MOD;                tmp = next[tmp];            }        }        printf("%d\n", ans);    }}