您的位置:首页 > 其它

Count the string

2018-01-29 20:30 281 查看
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

以已知字符串的前缀字符串为匹配串p,求匹配串p在已知字符串出现的次数和
#include<stdio.h>
#include<string.h>
#define mod 10007
using namespace std;
const int N = 200005;
char p
;
int next
;
void getNext(char p[],int m,int next[]){
int j=0;
int t=-1;
next[0]=-1;
int cnt=0;
while(j<m){
if(t<0||p[j]==p[t]){
next[++j]=++t;
if(next[j]>0) cnt++;
}
else t=next[t];
}
printf("%d\n",(cnt+m)%mod);
}
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
scanf("%s",p);
getNext(p,n,next);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: