链接:http://poj.org/problem?id=3461
KMP:
AC code:
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
char p[10005],q[1000005];
int nextval[10005];
void getnextval(char p[],int m)
{
int i,j=-1;
nextval[0]=-1;
for(i=1;i<m;++i)
{
while(j!=-1&&p[j+1]!=p[i])
j=nextval[j];
if(p[j+1]==p[i]) j++;
nextval[i]=j;
}
}
int KMP(char p[],char q[],int m,int n)
{
int i=0,j=-1,cnt=0;
for(i=0;i<n;++i)
{
while(j!=-1&&p[j+1]!=q[i])
j=nextval[j];
if(p[j+1]==q[i]) j++;
if(j==m-1) { cnt++; }
}
return cnt;
}
int main()
{
int test;
scanf("%d",&test);
while(test--)
{
scanf("%s%s",p,q);
int m=strlen(p),n=strlen(q);
getnextval(p,m);
printf("%d\n",KMP(p,q,m,n));
}
return 0;
}