hdu3336Count the string(kmp的next的使用

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7567    Accepted Submission(s): 3515


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
题意:
给你一个长度为n的字符串s1
abab sum=kmp(abab,a)+kmp(abab,ab)+kmp(abab,abc)+kmp(abab,abab);
#include <stdio.h>
#include <string.h>
const int MAX_LEN = 200005;
int next[MAX_LEN];
char s[MAX_LEN];
int cns[MAX_LEN];
int main()
{
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        int len;
        int flag;
        scanf("%d",&len);
        scanf("%s",s+1);   


        next[1] = 0;
        flag = 0;
        for(int i=2;i<=len;i++)
        {
            while(flag > 0 && s[flag+1]!=s[i])
                flag = next[flag];
            if(s[flag+1] == s[i])
                flag++;
            next[i] = flag;
        }//注意这里的和next数组不一样
/*for(int i = 1; i <= len; i++)
printf("%d ", next[i]);*/
        int sum=0;
        memset(cns,0,sizeof(cns));
        for(int i=1;i<=len;i++)
        {
            cns[i] = (cns[next[i]] + 1)%10007;//至今还没有明白这个动态转移方程
            sum = (sum+cns[i])%10007;
            printf("%d ",cns[i]);
        }
        printf("%d\n",sum);
    }
    return 0;
}
 

你可能感兴趣的:(动态规划,KMP)