您的位置:首页 > 其它

hrbust/哈理工oj 2060 截取方案数【KMP匹配】

2016-03-10 17:17 295 查看
截取方案数
Time Limit: 1000 MSMemory Limit: 32768 K
Total Submit: 165(70 users)Total Accepted: 68(58 users)Rating: 





Special Judge: No
Description
给定一个模式串T,主串S,问:从S中截取T有多少种方案?

Input
有多组测试数据,对于每组测试数据,第一行是模式串T,第二行是主串S,数据中仅包含大小写字母和数字,模式串T长度不超过10^4, 主串S长度不超过10^5。

注意:数据是随机的。

Output
对于每组测试数据,输出一行,为截取方案数。

Sample Input
abc
abcdaabcab
abcd
abcdaabcab
aba
abababa

Sample Output
2
1
3

Source
HCPC2014校赛训练赛 3
基础KMP匹配,如果匹配成功output++即可。

#include<stdio.h>
#include<string.h>
using namespace std;
int next[200005];
char a[2000005];
char b[2000005];
int lena;
int lenb;
int output;
void set_naxt()//子串的next数组
{
int i=0,j=-1;
next[0]=-1;
while(i<lenb)
{
if(j==-1||b[i]==b[j])
{
i++; j++;
next[i]=j;
}
else
j=next[j];
}
}

int kmp()
{
int i=0,j=0;
set_naxt();
while(i<lena)
{
if(j==-1||a[i]==b[j])
{
i++;j++;
}
else
j=next[j];
if(j==lenb)
{
output++;
}
}
}
int main()
{
while(~scanf("%s",b))
{
output=0;
scanf("%s",a);
lena=strlen(a);
lenb=strlen(b);
kmp();
printf("%d\n",output);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息