首页 > 代码库 > HDU - 3336 Count the string
HDU - 3336 Count the string
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.
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.
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[i]]的结果,因为我们知道next[i]数组代表的是和前缀匹配的长度,所以可以归纳到前缀中#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; const int maxn = 200005; const int mod = 10007; int dp[maxn], next[maxn], n; char pattern[maxn]; int getNext() { int m = strlen(pattern); next[0] = next[1] = 0; for (int i = 1; i < m; i++) { int j = next[i]; while (j && pattern[i] != pattern[j]) j = next[j]; next[i+1] = pattern[i] == pattern[j] ? j+1 : 0; } memset(dp, 0, sizeof(dp)); int sum = 0; for (int i = 1; i <= n; i++) { dp[i] = (dp[next[i]] + 1) % mod; sum = (sum + dp[i]) % mod; } return sum; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d", &n); scanf("%s", pattern); printf("%d\n", getNext()); } return 0; }
HDU - 3336 Count the string
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。