首页 > 其他 > 详细

HDU 3336 Count the string kmp+dp

时间:2014-03-25 17:33:09      阅读:398      评论:0      收藏:0      [点我收藏+]

Count the string

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


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
给你一个字符串,然后找出这个字符串的所有前缀,并计算它们在字符串中出现都次数,求次数和。
在kmp中next数组的含义是:next[i]表示前i个字符所组成的字符串最大前后缀匹配长度 。
如:next[i]=j,则s[1....j]=s[i-j+1.....i]。
dp【i】:以s[i]结尾的子串总共含前缀的数量。
dp[i]=dp[next[i]]+1;表示前i个字符中,最大前后缀匹配长度+本身。
//46MS	2016K
#include<stdio.h>
#include<string.h>
char text[200007],pattern[200007];
int next[200007],dp[200007];
int n;
void pre()
{
    int j=0;
    next[1]=0;
    for(int i=2;i<=n;i++)
    {
        while(j>0&&pattern[j+1]!=pattern[i])j=next[j];
        if(pattern[j+1]==pattern[i])j++;
        next[i]=j;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int count=0;
        scanf("%d%s",&n,pattern+1);
        pre();
        dp[0]=0;
        for(int i=1;i<=n;i++)
        {
            dp[i]=dp[next[i]]+1;
            count=(count+dp[i])%10007;
        }
        printf("%d\n",count);
    }
    return 0;
}



HDU 3336 Count the string kmp+dp,布布扣,bubuko.com

HDU 3336 Count the string kmp+dp

原文:http://blog.csdn.net/crescent__moon/article/details/22069791

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!