Count the string

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


题目意思:给你一个串,找出它所有的非空前缀,然后与主串进行匹配,将所有匹配成功的次数加起来

例如: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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值