Count the string HDU

来源:互联网 发布:mac pro13 retina壁纸 编辑:程序博客网 时间:2024/06/05 03:38
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专题的时候碰到的,所以就想到kmp上去了,否则没那么好想。我们知道,kmp的next数组其实是维护了当前下标i的前缀。那么如果你要求所有前缀出现的次数,就去一个一个地增加字符串的长度就可以了,这样肯定是可以遍历所有前缀的,但是我们如何求和呢。想一下,我设置一个dp【i】,代表前缀在前i个字符中出现的次数,那么当再次出现一个与前i个字符相同的字符串的出现次数就是dp【j】=dp【next【j】】+1,累加到sum中。可以知道,如果累加了dp【j】,那就说明也累加了多次dp【i】,多累加的一次,其实就是因为这两个字符串匹配而之前没有统计到。
AC代码:
#include<stdio.h>#include<string.h>using namespace std;const int M=2e5+10;char str[M];int dp[M],next[M];void getnext(int len){    next[0]=-1;    for(int i=1; i<len; i++)    {        int j=next[i-1];        while(j>=0&&str[i]!=str[j+1])            j=next[j];        if(str[i]==str[j+1])            next[i]=j+1;        else            next[i]=-1;    }}int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        scanf("%s",str);        getnext(n);        dp[0]=1;        int sum=0;        for(int i=1; i<n; i++)        {            int j=next[i];            if(j==-1)                dp[i]=1;            else                dp[i]=dp[j]+1;            sum+=dp[i];            sum%=10007;        }        printf("%d\n",sum+1);    }}