hdu3336Count the string(kmp的next的使用

小灰灰 2022-08-21 09:38 52阅读 0赞

Count the string

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7567 Accepted Submission(s): 3515

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. 1
  2. 4
  3. abab

Sample Output

  1. 6
  2. 题意:
  3. 给你一个长度为n的字符串s1
  4. abab sum=kmp(abab,a)+kmp(abab,ab)+kmp(abab,abc)+kmp(abab,abab);

#include
#include
const int MAX_LEN = 200005;
int next[MAX_LEN];
char s[MAX_LEN];
int cns[MAX_LEN];
int main()
{
int cas;
scanf(“%d”,&cas);
while(cas—)
{
int len;
int flag;
scanf(“%d”,&len);
scanf(“%s”,s+1);

  1. next\[1\] = 0;
  2. flag = 0;
  3. for(int i=2;i<=len;i++)
  4. \{
  5. while(flag > 0 && s\[flag+1\]!=s\[i\])
  6. flag = next\[flag\];
  7. if(s\[flag+1\] == s\[i\])
  8. flag++;
  9. next\[i\] = flag;
  10. \}//注意这里的和next数组不一样

/*for(int i = 1; i <= len; i++)
printf(“%d “, next[i]);*/
int sum=0;
memset(cns,0,sizeof(cns));
for(int i=1;i<=len;i++)
{
cns[i] = (cns[next[i]] + 1)%10007;//至今还没有明白这个动态转移方程
sum = (sum+cns[i])%10007;
printf(“%d “,cns[i]);
}
printf(“%d\n”,sum);
}
return 0;
}

发表评论

表情:
评论列表 (有 0 条评论,52人围观)

还没有评论,来说两句吧...

相关阅读