Count the string

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

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. 如果枚举每一个前缀字串,然后KMP匹配的话,会超时,所以我们要利用KMP的特性来巧妙计算。
  2. KMP中的next数组表示的是最长公共前后缀字串长度,基于这一个特点。每次遍历到 i ,对于 next[i] 来讲,又重复出现了前缀长度为next[i] 的字串,基于这一特点,我们由前向后推出每一个 i 处的所有前缀重复数,所谓DP。
  3. dp[i] = (dp[nxt[i]]+1)%mod; 即状态转移方程。也就是说,长度为 i 的前缀串中又多了一份长度为nxt[i]的前缀字串的个数,再加上自身,就是更新得到的数量。
const int mod = 10007;
const int MAX = 200005;
int dp[MAX];
int n;
int nxt[MAX];
char a[MAX];
void getnxt()
{
nxt[0] = -1;
int j = 0,k=-1;
while(j<n)
{
if(k==-1||a[j]==a[k])
nxt[++j] = ++k;
else
k = nxt[k];
}
}
int main()
{
int t;cin>>t;
while(t--)
{
cin>>n;
cin>>a;
getnxt();
long long ans = 0;
for(int i=1;i<=n;i++)
dp[i] = (dp[nxt[i]]+1)%mod;
for(int i=1;i<=n;i++)
ans = (ans+dp[i])%mod;
cout<<ans<<endl;
}
return 0;
}

最新文章

  1. Netty_UDP丢包解决
  2. WPF计算
  3. Entity Framework 基础知识走马观花
  4. Java Collection Framework概述
  5. 四种生成和解析XML文档的方法详解(介绍+优缺点比较+示例)
  6. NOIP2007 T2纪念品分组 解题报告-S.B.S.
  7. Unity获取方法的参数和方法名称
  8. XRDP与VNC的关系
  9. chrome开发工具指南(五)
  10. idea出现Error:Maven Resources Compiler: Maven project configuration required for module &#39;market&#39; isn&#39;t available.
  11. nginx 安装、启动、重启、关闭 (linux系统命令行)
  12. c# List列表数据转换成树形结构
  13. TensorFlow资源整理
  14. 执行monkey APK 制作
  15. 计算机基础知识 一 Basic knowledge of computers One
  16. Asp.net中FileUpload控件实现图片上传并带预览显示
  17. 【优化】bigpipe技术
  18. Qt 编译boost
  19. IE678下,select 诡异的样式
  20. python 写文件write(string), writelines(list) ,读文件

热门文章

  1. java 单例模式之线程安全的饿汉模式和懒汉模式
  2. svn更改账户信息
  3. 03-----Bootstrap的介绍
  4. ubuntu网络已禁用解决办法
  5. Spark最简安装
  6. 性能测试学习第六天_loadrunner录制的一些问题
  7. 小程序的switch组件
  8. 实现多行文字居中方法(兼容IE6)
  9. JQuery基础知识==认识JQuery
  10. 关于wav文件fft处理后x,y轴坐标数据的问题