HDU3336Count the string

http://acm.hdu.edu.cn/showproblem.php?pid=3336

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


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
貌视这个题有bug
题目大意就是求前i(1<=i<=n)个字母出现的次数的和
还是f数组的应用。样例abab      f[4]=2代表长度为4的子串中重复出现的是ab两个字母
所以做题的时候还要用num数组记录长度为f[i]的有几个

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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#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;
}



你可能感兴趣的:(KMP算法)