Count the string
Problem Description
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
Author
foreverlin@HNU
Source
HDOJ Monthly Contest – 2010.03.06
解题思路
dp[i]表示以s[i]前一个位置结尾可以得到的前缀串个数,因为你的s[f[i]]与s[i]时不同的,但是这个数组的的深层含义却是0-f[i]-1的这个前缀会以s[i]-1结尾,中会能匹配到这个前缀。
我们得到的f数组,,,,
所以当f[i]==0时,说明前面没有匹配项,dp[i]=1,及他本身
else dp[i]=dp[f[i]-1]+1;
代码:
#include<iostream>
#include<cstdio>
#include<ctime>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
#define INF 0x3f3f3f3f
#define clock CLOCKS_PER_SEC
#define cle(x) memset(x,0,sizeof(x))
#define maxcle(x) memset(x,0x3f,sizeof(x))
#define mincle(x) memset(x,-1,sizeof(x))
#define maxx(x1,x2,x3) max(x1,max(x2,x3))
#define minn(x1,x2,x3) min(x1,min(x2,x3))
#define cop(a,x) memcpy(x,a,sizeof(a))
#define FROP "hdu"
#define C(a,b) next_permutation(a,b)
#define LL long long
#define smin(x,tmp) x=min(x,tmp)
#define smax(x,tmp) x=max(x,tmp)
using namespace std;
const int mod=10007,N=200005;
char s[N];
int f[N];
int dp[N];
int T,n;
void get_fail()
{
f[0]=0,f[1]=0;
int j=0;
for(int i = 1; i < n; i++)
{
j=f[i];
while(j && s[j]^s[i])j=f[j];
f[i+1]=s[i]==s[j]?j+1:j;
}
}
int main()
{
freopen(FROP".in","r",stdin);
freopen(FROP".out","w",stdout);
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
scanf("%s",s);
get_fail();
dp[0]=1;
int sum=0;
for(int i = 1; i <= n; i++)
{
if(!f[i])dp[i]=1;
else
dp[i]=dp[f[i]-1]+1;
sum=(sum+dp[i])%mod;
}
printf("%d\n",sum);
}
return 0;
}