HDU 3336 Count the string
来源:互联网 发布:淘宝冲印上传系统 编辑:程序博客网 时间:2024/06/10 00:10
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
大概题意:给出一个字符串,对于每个前缀,都求出这个前缀在字符串s中的匹配次数。然后所有前缀的匹配次数为答案。
思路:1.先求出next数组。2.求所有next数组到-1前的值的和……到-1前就是和它匹配的数量……
#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn=200005;const int mod=10007;char s[maxn];int next1[maxn];void makenext(int n){ int i,k; next1[0]=-1; for(i=1,k=-1;i<n;i++) { while(k>-1&&s[i]!=s[k+1]) k=next1[k]; //printf("k=%d s[%d+1]=%c ",k,k,s[k+1]); //printf("%c %c ",s[i],s[k+1]); if(s[i]==s[k+1]) k++; next1[i]=k; }}int main(){ int T; scanf("%d",&T); while(T--) { int n,i; scanf("%d",&n); scanf("%s",s); makenext(n); // for(i=0;i<n;i++) // printf("next[%d]=%d ",i,next[i]); long long int ans=0,k; for(i=0;i<n;i++) { ans=(ans+1)%mod; k=next1[i]; while(k!=-1) { ans=(ans+1)%mod; k=next1[k]; } } printf("%I64d\n",ans); } return 0;}
做这道题内心毫无波澜,所以就不放表情包了……
- HDU 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- HDU-Count the string -3336
- hdu 3336 Count the string
- HDU 3336 Count the string
- HDU 3336Count the string
- HDU 3336Count the string
- hdu 3336 Count the string
- hdu 3336 count the string
- HDU 3336 Count the string
- HDU - 3336 Count the string
- hdu 3336 Count the string
- hdu 3336 Count the string
- servlet 的servletContext 对象
- 单片机扩展IO口
- JS对数组的操作
- poj1833排列
- 机器视觉之图像入门
- HDU 3336 Count the string
- Android EditText 监听回车键
- Zookeeper的安装和配置
- Eclipse+Maven创建webapp项目
- 解释器模式
- 第十周项目1——二叉树算法库
- Zookeeper服务器集群的搭建
- poj 3278 Catch That Cow bfs
- 链接分析学习