Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5060 Accepted Submission(s): 2380
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.
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.
1 4 abab
6
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#include <stack>
#define maxn 10000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 10007
#define PI 3.141592657
#define INF 1<<30
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
bool cmp(int a,int b){
return a>b;
}
char p[200005];
int f[200005];
int num[200005];
void getFail(char* p, int* f,int n)
{
int m = n;
f[0] = 0;
f[1] = 0;
for (int i = 1; i < m; i++)
{
int j = f[i];
while (j && p[i] != p[j])
{
j = f[j];
}
f[i + 1] = p[i] == p[j] ? j + 1 : 0;
}
}
int sum;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t,m;
cin>>t;
while(t--)
{
cle(num);
cin>>m;
scanf("%s",p);
getFail(p,f,m);
for(int i=1;i<=m;i++)
{
num[f[i]]=(num[f[i]]+1)%mod;///num[f[i]]++;
}
sum=0;
for(int i=1;i<=m;i++)
{
if(num[i]!=0)
sum=(sum+1+num[i])%mod;///加上它本身
else sum=(sum+1)%mod;
}
printf("%d\n",sum);
}
return 0;
}