hdu 1686 Oulipo
http://acm.hdu.edu.cn/showproblem.php?pid=1686
KMP算法,今天又到了好晚,不过今天总的来说收获还是很大的,做了好几道KMP的题目,呵呵,心情也还不错,这是一道纯模版题,感觉很简单,就是去b中找a的个数,当j=m的时候说明一个字符串匹配成功,然后求输出个数即可。。。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int next[1000000],m,n;
char a[1000000],b[1000000];
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(i<m)
{
if(j==-1||a[i]==a[j])
next[++i]=++j;
else
j=next[j];
}
}
int kmp()
{
int i=0,j=0;
int num=0;
while(i<n)
{
if(a[j]==b[i]||j==-1)
{
i++;j++;
}
else
j=next[j];
if(j==m)
{
num++;
j=next[j];
}
}
return num;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",a,b);
n=strlen(b);m=strlen(a);
getnext();
printf("%d\n",kmp());
}
// system("pause");
return 0;
}