J - 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

统计前缀字符串在文本串中出现的次数。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=2e5+10;
const int mod=10007;
char a[maxn];
int ne[maxn];
int vis[maxn];
void get(int len)
{
	ne[0]=-1;
	for(int i=0,j=-1;i<len;)
	{
		if(j==-1||a[i]==a[j]) ne[++i]=++j;
		else j=ne[j];
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int len;
		scanf("%d",&len);
		scanf("%s",a);
		get(len);
		for(int i=0;i<len;i++) vis[i]=0;
		for(int i=1;i<=len;i++)
		{
			vis[ne[i]]++;
		}
		int ans=0;
		for(int i=1;i<=len;i++) 
		{
			ans=(ans+vis[i])%mod;
		}
		printf("%d\n",(ans+len)%mod);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/85029433
今日推荐