截取方案数
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submit: 252(110 users) Total Accepted: 109(92 users) Rating: Special Judge: No
Description
给定一个模式串T,主串S,问:从S中截取T有多少种方案?
Input
有多组测试数据,对于每组测试数据,第一行是模式串T,第二行是主串S,数据中仅包含大小写字母和数字,模式串T长度不超过104,主串S长度不超过105。
注意:数据是随机的。
Output
对于每组测试数据,输出一行,为截取方案数。
Sample Input
abc
abcdaabcab
abcd
abcdaabcab
aba
abababa
Sample Output
2
1
3
直接套用KMP模板
(不知道KMP是什么的自行GOOGLE)
#include<stdio.h>
#include<string.h>
char t[10008],s[100008];
int next[10008];
void kmp_pre(int len)
{
int i,j;
j=next[0]=-1;
i=0;
while(i<len)
{
while(-1!=j && t[i]!=t[j])j=next[j];
next[++i]=++j;
}
}
int kmpcount(int lent,int lens)
{
int i,j;
int ans=0;
i=j=0;
while(i<lens)
{
while(-1!=j&&s[i]!=t[j])j=next[j];
i++;j++;
if(j>=lent)
{
ans++;
j=next[j];
}
}
return ans;
}
int main()
{
while(scanf("%s",t)!=EOF)
{
int lent=strlen(t);
kmp_pre(lent);
scanf("%s",s);
int lens=strlen(s);
printf("%d\n",kmpcount(lent,lens));
}
return 0;
}