HDU 3336 Count the string(KMP+稍微DP+next数组的运用)

喜欢ヅ旅行 2022-06-10 14:22 191阅读 0赞

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

题解:

给你一个长度为len的字符串问你他的所有前缀和是多少

比如abab

前缀a出现2次,ab出现2次,aba一次,abab一次所以是6

由于Next储存的是当前的后缀和前面的前缀的匹配情况,所以我们就稍微dp一下,对于每一个字符i,dp[i]=dp[next[i]]+1,就是当前前缀的次数,也就是说,当前的前缀等于前面那个前缀的出现次数+1

代码:

  1. #include<algorithm>
  2. #include<iostream>
  3. #include<cstring>
  4. #include<stdio.h>
  5. #include<math.h>
  6. #include<string>
  7. #include<stdio.h>
  8. #include<queue>
  9. #include<stack>
  10. #include<map>
  11. #include<vector>
  12. #include<deque>
  13. using namespace std;
  14. #define lson k*2
  15. #define rson k*2+1
  16. #define M (t[k].l+t[k].r)/2
  17. #define INF 1008611111
  18. #define ll long long
  19. #define eps 1e-15
  20. char T[200005];
  21. int Next[200005];
  22. int dp[200005];
  23. void init()
  24. {
  25. int i=0,j=-1;
  26. Next[0]=-1;
  27. while(T[i])
  28. {
  29. if(j==-1||T[j]==T[i])
  30. {
  31. i++;
  32. j++;
  33. Next[i]=j;
  34. }
  35. else
  36. j=Next[j];
  37. }
  38. }
  39. int main()
  40. {
  41. int i,j,len,test;
  42. int sum;
  43. int N=10007;
  44. scanf("%d",&test);
  45. while(test--)
  46. {
  47. scanf("%d",&len);
  48. scanf("%s",T);
  49. init();
  50. dp[0]=0;
  51. dp[1]=1;
  52. sum=0;
  53. for(i=1;i<=len;i++)
  54. {
  55. dp[i]=(dp[Next[i]]+1)%N;
  56. sum=(sum+dp[i])%N;
  57. }
  58. printf("%d\n",sum);
  59. }
  60. return 0;
  61. }

发表评论

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

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

相关阅读

    相关 运用

    一种数据类型(引用类型) 1、动态初始化:数据类型\[\] 数组名=new 数据类型\[大小\];int\[\] a=new int\[10\]; 数组的引用:数组名\[下