ACM-KMP之Count the string——hdu3336

Count the string

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


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算法,总算差不多了,做两道题来练练手吧 \(^o^)/

这道题目是KMP算法,对Next数组的活用。

题意就是输入 一个字符串,判断它的子串从0到i(i<=长度) 在主串出现的次数之和。

题中也给出了  abab子串有a,ab,aba,abab  分别在主串出现了2,2,1,1 共6次。


题目解法,跟Next数组创建有关系,Next数组查询的时候会用到回溯,这就证明了,你所要找的串,之前出现过,

这样就可以根据回溯的次数来计算出现次数了。

比如题目中的

序号    0  1  2  3  4

字符串  a  b  a  b

next   -1  0  0  1  2

从j=1开始,1回溯一次 sum+=1,j=2的时候也是一次,sum+=1,j=3与j=4时分别回溯两次,sum+=2,sum+=2。

所以总共六次。


KMP的next数组求法可看:http://blog.csdn.net/lttree/article/details/20733857


代码咯:

#include <stdio.h>
#include <string.h>
using namespace std;
char c[200001];
int next[200001];
int len;

// 求next数组
void Get_next()
{
    int i,j;
	next[0]=-1;
	i=0;
	j=-1;
	while(i<len)
	{
	    if(j==-1 || c[i]==c[j])
	    {
	       next[++i]=++j;
	    }
	    else    j=next[j];
	}
}

int search()
{
	int i,j;

	int sum=0;
	for(i=1;i<=len;++i)
	{
	    j=i;
	    while(j)
	    {
	        sum=(sum+1)%10007;
	        j=next[j];
	    }
	}

	return sum;
}

int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
	    memset(next,0,sizeof(next));
	    scanf("%d",&len);
	    scanf("%s",c);

        Get_next();

        printf("%d\n",search());
	}
	return 0;
}


你可能感兴趣的:(String,KMP,ACM,count,the,hdu3336)