Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4845 Accepted Submission(s): 2295
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.
//Hello. I'm Peter.
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<cctype>
#include<ctime>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef long double ld;
#define peter cout<<"i am peter"<<endl
#define input freopen("data.txt","r",stdin)
#define randin srand((unsigned int)time(NULL))
#define INT (0x3f3f3f3f)*2
#define LL (0x3f3f3f3f3f3f3f3f)*2
#define gsize(a) (int)a.size()
#define len(a) (int)strlen(a)
#define slen(s) (int)s.length()
#define pb(a) push_back(a)
#define clr(a) memset(a,0,sizeof(a))
#define clr_minus1(a) memset(a,-1,sizeof(a))
#define clr_INT(a) memset(a,INT,sizeof(a))
#define clr_true(a) memset(a,true,sizeof(a))
#define clr_false(a) memset(a,false,sizeof(a))
#define clr_queue(q) while(!q.empty()) q.pop()
#define clr_stack(s) while(!s.empty()) s.pop()
#define rep(i, a, b) for (int i = a; i < b; i++)
#define dep(i, a, b) for (int i = a; i > b; i--)
#define repin(i, a, b) for (int i = a; i <= b; i++)
#define depin(i, a, b) for (int i = a; i >= b; i--)
#define pi 3.1415926535898
#define eps 1e-6
#define MOD 10007
#define MAXN
#define N 200100
#define M
int nextpos[N],n,ans[N],lastans;
//nextpos是kmp算法中的next數組
//ans表示從0到i這個串中前綴後綴總數,就是答案的一部分
char s[N];
void build_nextpos()
{//kmp算法中最重要的next數組
int i,j;
i=0;
j=-1;
nextpos[0]=-1;
while(i<n)
{
if(j==-1 || s[i]==s[j])
{
nextpos[i+1]=j+1;
i++;
j=j+1;
}
else j=nextpos[j];
}
}
int main()
{
int T,j;
cin>>T;
while(T--)
{
scanf("%d %s",&n,s);
repin(i,0,n)
{
ans[i]=0;
}
build_nextpos();
repin(i,0,n)
{
j=nextpos[i];
if(j>0 && i>0)
{//dp方程
ans[i-1]=ans[j-1]+1;
ans[i-1]%=MOD;
}
}
lastans=0;
rep(i,0,n)
{//最後統計答案
lastans+=ans[i];
lastans%=MOD;
}
//由於每個串本身還要算一次,所以+n
lastans+=n;
lastans%=MOD;
printf("%d\n",lastans);
}
}