您的位置:首页 > 其它

hdu3336-kmp应用其实也也可以不用

2018-02-05 21:46 239 查看


Count the string

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

Total Submission(s): 12333    Accepted Submission(s): 5691


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
#include <iostream>
#include <cstring>
#include<stdio.h>//不能用using namespace std或者把next命名改掉;因为next存在命名重复会CE编译却不报错,~~好可恶找了半天,咨询了一下别人才解决
int next[200003];
char T[200003];
int tlen;
void getNext()
{
int j, k;
j = 0;
k = -1;
next[0]=-1;
while(j < tlen)
if(k == -1 || T[j] == T[k])
next[++j] = ++k;
else
k = next[k];
}
int main()
{

int t;
scanf("%d",&t);
int n;
while(t--)
{
scanf("%d",&n);
memset(next,0,sizeof(next));
// getchar();可以去掉的原因是%s不接受空串,所以不会影响T字符串的输入
scanf("%s",T);
tlen = strlen(T);
getNext();
int sum[200003]={0};
int summ=0;
for(int i=2;i<=n;i++)//字符串下标是从0开始,在0,1下标之前不可能存在长度为1(最小了)的前缀和后缀相等的情况。next[i]代表在i位置前相等的最长前后缀//前后缀举例abaa:前缀{a,ab,aba}后缀{baa,aa,a}//
{
sum[next[i]]++;
}
for(int j=1;j<n;j++)//j代表前缀的长度
{
summ+=sum[j];
summ%=10007;
}
printf("%d\n",(summ+n)%10007);//加n是因为每个前缀和本身都算一,前两个for循环求得是除了各个前缀以外相同的个数
}
return 0;
}
第二种方案
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
int n,m,i,j,k,l;
char s[222222];
cin>>m;
while(m--)
{   cin>>n;
cin>>s;k=n%10007;
for(i=1;i<n;i++)
{
l=i;j=0;  //每次都是用j=0从第一个开始匹配,l=i代替i向后滑动
while(l<n&&j<n)
if(s[l++]==s[j++])
k=(k+1)%10007;  //成功一个就加一
else break;
}
cout<<k<<endl;
}
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp
相关文章推荐