Hdu 1686
求模式串出现在目标串的次数
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
//#pragma comment(linker, "/STACK:102400000,102400000")
/*
hdu 1686 KMP简单题
求模式串出现在目标串的次数
*/
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF=0x3f3f3f3f;
const int mod = 1e9+7;
const int N=1000010;
char s[N],p[N];
int net[N];
void getnext(int len)
{
int k = -1;
net[0] = -1;
for(int i = 1; i < len; i++)
{
while(k!=-1 && p[k+1]!=p[i])
k = net[k];
if(p[k+1]==p[i])
k++;
net[i] = k;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",p,s);
int lenp = strlen(p);
getnext(lenp);
int lens = strlen(s);
int k = -1;
int num = 0;
for(int i = 0; i < lens; i++)
{
while(k!=-1 && p[k+1]!=s[i])
k = net[k];
if(p[k+1]==s[i])
k++;
if(k==lenp-1)
{
k = net[k];
num++;
}
}
printf("%d\n",num);
}
return 0;
}