计算字符串问题
2015-05-14 13:34
120 查看
问题:给你一个字符串,然后让你把所有的前缀给找出来,并把它们在字符串中的出现次数相加,输出这个和写出算法。
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
回答:主要考察KMP算法运用
#include<cstdio>
#include<cstring>
int n,m;
char b[200010];
int p[200010];
void get_p(){
p[1]=0;
int i,j=0;
for(i=2;i<=m;i++){
while(j>0&&b[j+1]!=b[i]) j=p[j];
if(b[j+1]==b[i]) j+=1;
p[i]=j;
}
}
int dp[200010];//dp【i】:以string[i]结尾的子串总共含前缀的数量
int main(){
int t,i;
scanf("%d",&t);
while(t--){
scanf("%d",&m);
scanf("%s",b+1);
get_p();printf("%d\n",p[9]);
dp[0]=0;
int sum=0;
for(i=1;i<=m;i++){
dp[i]=dp[p[i]]+1;
sum=(sum+dp[i])%10007;
}
printf("%d\n",sum);
}
return 0;
}
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
回答:主要考察KMP算法运用
#include<cstdio>
#include<cstring>
int n,m;
char b[200010];
int p[200010];
void get_p(){
p[1]=0;
int i,j=0;
for(i=2;i<=m;i++){
while(j>0&&b[j+1]!=b[i]) j=p[j];
if(b[j+1]==b[i]) j+=1;
p[i]=j;
}
}
int dp[200010];//dp【i】:以string[i]结尾的子串总共含前缀的数量
int main(){
int t,i;
scanf("%d",&t);
while(t--){
scanf("%d",&m);
scanf("%s",b+1);
get_p();printf("%d\n",p[9]);
dp[0]=0;
int sum=0;
for(i=1;i<=m;i++){
dp[i]=dp[p[i]]+1;
sum=(sum+dp[i])%10007;
}
printf("%d\n",sum);
}
return 0;
}
相关文章推荐
- Cardinality Estimation算法学习(一)(了解基数计算的基本概念及回顾求字符串中不重复元素的个数的问题)
- 记一次js中和php中的字符串长度计算截取的终极问题和完美解决方案
- 计算 24 点是一种扑克牌益智游戏,随机抽出 4 张扑克牌,通过加 (+) ,减 (-) ,乘 ( * ), 除 (/) 四种运算法则计算得到整数 24 ,本问题中,扑克牌通过如下字符或者字符串表示,其中,小写 joker 表示小王,大写 JOKER 表示大王:
- 在C#中解决动态计算表达式的问题(如字符串"Sin(1)+Cos(2)",执行并得出结果)
- 计算4000000000内的最大f(n)=n值---字符串的问题python实现(五岁以下儿童)
- 计算4000000000以内最大的f(n)=n的值---字符串问题python实现(五)
- 《编程之美》- 3.3 - 计算字符串相似度 即 最小编辑距离问题
- 3.1_计算字符串移位包含问题
- C语言:关于计算字符串中空格数的问题
- GEF常见问题7:计算字符串在画布上占据的空间
- 字符串碎片问题,例如“aaabbaaac”是由下面碎片组成“aaa”,"bb","c",则计算所有碎片的平均长度
- Trie树的编程实现,用于计算字符串出现次数,求公共前缀字符串等问题
- C语言:关于计算字符串中空格数的问题
- 记一次js中和php中的字符串长度计算截取的终极问题和完美解决方案
- as3计算字符串和数字相加时的悲催问题
- 含软连字符的字符串计算显示长度的问题
- 命令行输入的字符串的长度计算问题
- 含软连字符的字符串计算显示长度的问题
- 字符串匹配问题:输入一个字符串,计算其中包含的‘连续’给定的子字符串最长的个数.
- 含软连字符的字符串计算显示长度的问题