HDU 3336 Count the string

Count the string

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



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
 
题意是求每个前缀的在总串中的出现次数。

根据KMP求出的next数组的值的含义,可以得到以当前位作为后缀的串与前缀一个next[i]长度的串相同。

有了这个想到了什么?

没错,就是DP,这个需要动态规划的思想来求解最后的答案。

得到了next的值,如果之前出现过,那么就有dp[i] = dp[next[i]] + 1对不对。dp数组这里表示的是以i位为结尾的串的总的个数

比如abab,对应的next数组是0012,得到的dp是1122,分别代表a出现一次,ab出现一次,a出现一次和aba出现一次,ab出现一次和abab出现一次。

代码如下:

/*************************************************************************
	> File Name: Count_the_string.cpp
	> Author: Zhanghaoran
	> Mail: chilumanxi@xiyoulinux.org
	> Created Time: Wed 02 Dec 2015 06:06:13 PM CST
 ************************************************************************/

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>

using namespace std;

void prekmp(char x[], int m, int kmpnext[]){
    int i, j;
    i = 0;
    j = kmpnext[0] = -1;
    while(i < m){
        while(j != -1 && x[i] != x[j]){
            j = kmpnext[j];
        }
        kmpnext[++ i] = ++ j;
    }
}

int T;
int nexti[200010];
char str[200010];
int m;
int dp[200010];
int main(void){
    cin >> T;
    while(T --){
        cin >> m;
        cin >> str;
        prekmp(str, m, nexti);
        int sum = 0;
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= m; i ++){
            dp[i] = (dp[nexti[i]] + 1) % 10007;
            sum = (sum + dp[i]) % 10007;
        }
        cout << sum << endl;
    }
}


posted @ 2015-12-03 00:28  ChiLuManXi  阅读(149)  评论(0编辑  收藏  举报