Count the string HDU - 3336 KMP+DP

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
思路:这是我在做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);
    }
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值