首先给出KMP模板:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
const int maxn = 1e4+7;
char text[maxn*100], pat[maxn];
int lent, lenp, nextp[maxn];
void get_next() {
int i, j = -1;
nextp[0] = -1;
for(i = 1; i <= lenp;i++) {
while(j > -1&&pat[j+1] != pat[i]) j = nextp[j];
if(pat[j + 1] == pat[i]) j++;
nextp[i] = j;
}
}
int KMP() {
int ans = 0, i = 0, j = -1;
get_next();
for(i = 0; i < lent; i++) {
while(j != -1&&pat[j+1] != text[i]) {
j = nextp[j];
}
if(pat[j+1] == text[i]) j = j + 1;
if(j == lenp - 1) ans++;
}
return ans; //返回匹配串的个数;
}
int main()
{
int t;
scanf("%d", &t);
while(t--) {
scanf("%s%s", pat, text);
lent = strlen(text);
lenp = strlen(pat);
printf("%d\n", KMP());
}
return 0;
}