您的位置:首页 > 其它

HDU 3336 Count the string(KMP 理解)

2013-07-16 11:09 459 查看


Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3002    Accepted Submission(s): 1397


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

HDOJ Monthly Contest – 2010.03.06

 

Recommend

lcy

 
这个题目好像有点歧义,不过不要想太多,直接在next值上作文章就OK 了
这个next值记录的就是当前位置向前 多少个和这个字符串开头多少个相等
有了这样我们只要记录每个next值对应有多少个,然后加上n个自身的一个匹配就OK 了!
这个题目的关键还是对KMP的理解,本质上kmp的next就是表示串内关系的一个值,理解KMP
是理解AC自动机的基础

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char str[200001];
int next[200001];
int rec[200001];
int n;
int get_next()
{
int i=0,j=-1;
next[0]=-1;
while(str[i])
{
if(j==-1 || str[i]==str[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
return 0;
}
int main()
{
int t,i,j;
int ans;
scanf("%d",&t);
while(t--)
{
ans=0;
scanf("%d",&n);
scanf("%s",str);
memset(rec,0,sizeof(rec));
str
='a';
str[n+1]=0;
get_next();
for(i=1;i<=n;i++)
rec[next[i]]++;
for(i=1;i<=n;i++)
if(rec[i] > 0)
{
ans+=rec[i];
ans%=10007;
}
ans+=n;
printf("%d\n",ans%10007);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  KMP