码迷,mamicode.com
首页 > 其他好文 > 详细

HDOJ Count the string 3336【KMP】

时间:2015-08-07 16:12:50      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6302    Accepted Submission(s): 2919


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
 

Author
foreverlin@HNU
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  3746 1358 3341 2222 3068 
 


题意:给你一个串,找出它的前缀,然后再找出它前缀在这个串里面出现几次。

解题思路:肯定不能枚举所有前缀  跟此串比较 肯定TLE。。怎么办?肯定KMP这是毫无疑问的,但是得想到利用next数组的思想,因为每一个next数组保存的就是最长的前缀。如何判断一个前缀在串里面出现的次数?假设我们找到截止到i位置的前缀,那么我们找到这个公共前缀的位置,让公共前缀位置上的值加1 就等于位置,递推式就是

d [ i ] = d [ next[ i ] ] + 1.

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define maxn 200000+20
using namespace std;

char P[maxn];
int pre[maxn];

void getnext(int n)
{
	pre[0]=pre[1]=0;
	for(int i=1;i<n;i++){
		int k=pre[i];
		while(k&&P[k]!=P[i])k=pre[k];
		pre[i+1]=P[i]==P[k]?k+1:0;
	}
}

int main()
{
	int t;
	scanf("%d",&t);
	while(t--){
		int d[maxn];
		int n;
		scanf("%d",&n);
		scanf("%s",P);
		getnext(n);
		int sum=0;
		for(int i=1;i<=n;i++){//注意此处下标
			d[i]=d[pre[i]]+1;
			sum=(sum+d[i])%10007;
		}
		printf("%d\n",sum);
	}
	return 0;
} 


版权声明:本文为博主原创文章,转载请注明出处。

HDOJ Count the string 3336【KMP】

标签:

原文地址:http://blog.csdn.net/ydd97/article/details/47339877

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!