HDU3336 Count the string
Count the string
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.
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.
InputThe 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.
OutputFor 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复杂度为O(n^2),肯定不行。考虑next数组的性质,如果已经直到所有前缀在s[0...k-1]内的匹配数dp[k],k = next[i],再把s[k...i-1]这段字符串考虑在内的话,新增加的前缀匹配数为dp[k]+1(s[0...k-1]所有非本身的子串与s[k...i-1]的匹配数为dp[k],
s[0...k-1]本身与s[k...i-1]的匹配数为1),sum求所有i的dp和即可。
1 #include <bits/stdc++.h> 2 using namespace std; 3 int T,n,sum; 4 int dp[200005],nxt[200005]; 5 char s[200005]; 6 7 void getnext(){ 8 int i = 0,j = nxt[0] = -1; 9 while(i < n){ 10 while(j != -1 && s[j] != s[i]) j = nxt[j]; 11 nxt[++i] = ++j; 12 } 13 } 14 15 int main(){ 16 scanf("%d",&T); 17 while(T--){ 18 scanf("%d",&n); 19 scanf("%s",s); 20 getnext(); 21 dp[0] = 0; 22 sum = 0; 23 for (int i = 1;i <= n;++i){ 24 dp[i] = dp[nxt[i]]+1; 25 sum = (sum + dp[i]) % 10007; 26 } 27 printf("%d\n",sum); 28 } 29 }
)