首页 > 代码库 > 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.
 

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[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