HDU 3336 Count the string(KMP+DP)

Count the string

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


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最大可以达到200000,如果对于每个前缀用一次KMP会TLE。
首先定义一个tmp数组,tmp[i]表示以i结尾的字符串的所有前缀出现次数之和。
KMP的Next数组保存的是从s[0]到s[i]的最大公共前后缀长度,即从s[0]到s[Next[i]-1]与s[i-Next[i]]到s[i-1]这一点的字符串是完全重合的。所有以i结尾的字符串的所有前缀出现次数之和即tmp[i]为以Next[i]-1结尾的字符串的所有前缀出现次数之和再加上1。

所有状态转移方程就是tmp[i]=(tmp[Next[i-1]]+1)%MOD。

参考代码:

#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>
#include<ctime>
#include<vector>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef long long LL;
const double pi=3.141592653;
const double eps=1e-10;
const int INF=0x3f3f3f3f;
const int MOD=10007;
const int MAXN=2e6+50;

int n,Next[MAXN],tmp[MAXN];
char a[MAXN];

void getNext(char* B)
{
    Next[0]=0;
    for(int i=1; i<n; i++)
    {
        int k=Next[i-1];
        while(B[i]!=B[k]&&k)
            k=Next[k-1];
        Next[i]=B[i]==B[k]?k+1:0;
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%s",&n,a);
        getNext(a);
        int ans=0;
        memset(tmp,0,sizeof(tmp));
        for(int i=1;i<=n;i++)
        {
            tmp[i]=(tmp[Next[i-1]]+1)%MOD;
            ans=(ans+tmp[i])%MOD;
        }
        printf("%d\n",ans%MOD);
    }
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值