Count the string

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 32768/32768 K (Java/Others)

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


解题心得:

  1. 题意就是给你一个字符串,问你字符串中和每个前缀匹配的子串有多少个,可以前缀和前缀自身匹配。
  2. 其实就是一个对于next数组的理解,next数组记录的就是当前字符为后缀匹配的前缀,所以很简单,直接next匹配的时候记录总数就可以了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<string>
using namespace std;
const int maxn = 2e5+100;
const int MOD = 10007;
char s[maxn];
int Next[maxn]; int cal_next(int n){
int ans = 1;
int k = -1;
Next[0] = -1;
for(int i=1;i<n;i++){
ans++;//自身和自身匹配
ans %= MOD;
while(k > -1 && s[k+1] != s[i])
k = Next[k];
if(s[k+1] == s[i]){
k++;
ans++;
ans %= MOD;
}
Next[i] = k;
}
return ans%MOD;
} int main() {
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
scanf("%s",s);
int ans = cal_next(n);
printf("%d\n",ans);
}
return 0;
}

最新文章

  1. 模仿JavaAppArguments.java示例,编写一个程序,此程序从命令行接收多个数 字,求和之后输出结果,写出其的设计思想、程序流程图、源程序代码。
  2. 7月17日——高校就业信息网站功能及数据获取之python爬虫
  3. java异常处理机制
  4. web端测试和移动端测试的区别小记
  5. Ten Tips for Writing CS Papers, Part 2
  6. 适配 iOS尺寸
  7. ubuntu文件定时加密压缩
  8. JQuery 知识点
  9. Oracle中MERGE语句的使用
  10. 【转】angularjs指令中的compile与link函数详解
  11. 实现响应式——Bootstrap的删格系统详解
  12. vsftp实现只能上传不能下载、删除权限配置
  13. Android Service基础
  14. FJUTOJ-周赛2016-12-16
  15. 在Eclipse中使用git把项目导入到git中--转载
  16. 关于怎样获取DevExpress GridView过滤后或排序后的数据集问题(转)
  17. Jenkins的初级应用(2)-Invoke Phing targets
  18. 不停机修改线上 MySQL 主键字段 以及其带来的问题和总结思考
  19. [JSON]初识JSON
  20. [BUAA软工]第二次博客作业---结对编程

热门文章

  1. erlang通讯解析浮点数的一些问题
  2. DockerSwarm 微服务部署
  3. 原生css3作响应式布局
  4. Eucalyptus镜像管理
  5. 【Android开发笔记】底部菜单栏 FragmentTabHost
  6. (转载)office 2003 gaozhi.msi 缺失提示问题修复
  7. 一个SAP顾问在美国的这些年
  8. 【BZOJ2242】[SDOI2011] 计算器(数学模板三合一)
  9. python_69_内置函数1
  10. python读取文件指定行