hiho 1015 KMP

时间:2023-03-09 02:18:40
hiho 1015 KMP

input

1<=T<=20

string1 1<=strlen(string1)<=1e4

string2 2<=strlen(string2)<=1e6

output

string1在string2出现的次数

在第i位不匹配时跳到idx[i-1]位继续匹配

 #include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <ctime>
#include <cmath> using namespace std; const int N=1e6+;
int idx[N],T;
char a[N],b[]; void Next()
{
idx[]=;
for(int i=,j=;b[i];i++)
{
while(j&&b[i]!=b[j])
j=idx[j-];
b[i]==b[j]?idx[i]=++j:idx[i]=j;
}
} int kmp()
{
int c=,i,j;
for(i=,j=;a[i];i++)
{
if(!b[j]) c++;
if(a[i]!=b[j])
{
while(j)
{
j=idx[j-];
if(b[j]==a[i])
{
j++;
break;
}
}
}
else j++;
}
if(!b[j]) c++;
return c;
} int main()
{
//freopen("/home/user/桌面/in","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%s%s",b,a);
Next();
//for(int i=0;b[i];i++) printf("%d ",idx[i]);printf("\n");
printf("%d\n",kmp());
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return ;
}