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: [email protected]
	> 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;
    }
}


發佈了136 篇原創文章 · 獲贊 15 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章