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
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.
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.
根據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;
}
}