您的位置:首页 > 其它

Count the string

2017-07-21 17:43 120 查看
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. 

InputThe 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. 

OutputFor 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

题目意思:给你一个串,找出它所有的非空前缀,然后与主串进行匹配,将所有匹配成功的次数加起来
例如:abab的前缀a,ab,aba,abab,分别是2,2,1,1,总数为6。
解题思路:也是想了很久总想从next数组下手,可是没有找到规律(谁会用next数组写请教一下我),
最后还是暴力求解,果然超时,最后优化了一下A了。
其实不需要比较所有前缀,当你在比较的时候如果碰到一个前缀只能和自己匹配时,那么后面
的串都不用比较了,因为后面的串也只能匹配一次。
还有个要注意的是题目中有这一句话:The answer may be very large, so output the

answer mod 10007.所以输出时有大于10007的需要%10007。

#include<iostream>
#include<cstring>

using namespace std;

int const maxn=200100;

char str[maxn];
int next1[maxn];
int len;

void sign()
{

int i,j;
next1[0]=-1;
i=-1,j=0;
len=strlen(str);
while(j<len)
{
if(i==-1||str[i]==str[j])
{
i++;
j++;
next1[j]=i;
}
else
{
i=next1[i];
}
}
}

int main()
{
int T,num,len;
cin>>T;
while(T--)
{
num=0;
cin>>len;
for(int i=0;i<len;i++)
{
cin>>str[i];
}
memset(next1,0,sizeof(next1));
sign();
for(int i=len;i>0;i--)
{
if(next1[i]>0)
{
num++;
}
}
num+=len;
num=num%10007;
cout<<num<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: