#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
char a[1000010],b[1001000];
int next[1001000];
int n,m;
void GetNext(char ch[],int next[])
{
int i=1,j=0;
next[1]=0;
next[0]=0;
while(i<=n)
{
if(j==0||ch[i]==ch[j])
{
++i;++j;next[i]=j;
}
else
j=next[j];
}
}
int KMPIndex(char b[],char a[],int next[])
{
int i=1,j=1,count=0;
if(m<n)
return 0;
while(i<=m)
{
if(j==0||a[j]==b[i])
{
++i;++j;
}
else
j=next[j];
if(j==n+1) {count++;j=next[j];}
}
return count;
}
int main()
{
int pos,t;
int i,j;
scanf("%d",&t);a[0]='#';b[0]='#';
while(t--)
{
scanf("%s",a+1);
n=strlen(a)-1;
scanf("%s",b+1);
m=strlen(b)-1;
memset(next,0,sizeof(next));
GetNext(a,next);
pos=KMPIndex(b,a,next);
printf("%d\n",pos);
}
return 0;
}
poj3461KMP算法模板
最新推荐文章于 2025-09-06 17:14:26 发布
