#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10, M = 1e4 + 10;
int Next[N], f[N];
int n;
char s[N], p[M];
int slen, plen;
void get_next()
{
Next[1] = 0;
for(int i = 2, j = 0; i <= plen; i++)
{
while(j && p[i] != p[j + 1]) j = Next[j];
if(p[i] == p[j + 1]) j++;
Next[i] = j;
}
}
void cal_f()
{
int cnt = 0;
for(int i = 1, j = 0; i <= slen; i++)
{
while(j && (j == plen || s[i] != p[j + 1])) j = Next[j];
if(s[i] == p[j + 1]) j++;
f[i] = j;
if(f[i] == plen) cnt ++;
}
cout << cnt << endl;
}
int main(){
cin >> n;
while(n--)
{
getchar();
scanf("%s", p + 1);
scanf("%s", s + 1);
slen = strlen(s + 1);
plen = strlen(p + 1);
get_next();
cal_f();
}
return 0;
}
HDU - 1711 ( Number Sequence )
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10, M = 1e4 + 10;
int Next[N], f[N];
int n;
int s[N], p[M];
int slen, plen;
void get_next()
{
Next[1] = 0;
for(int i = 2, j = 0; i <= plen; i++)
{
while(j && p[i] != p[j + 1]) j = Next[j];
if(p[i] == p[j + 1]) j++;
Next[i] = j;
}
}
int cal_f()
{
for(int i = 1, j = 0; i <= slen; i++)
{
while(j && (j == plen || s[i] != p[j + 1])) j = Next[j];
if(s[i] == p[j + 1]) j++;
f[i] = j;
if(f[i] == plen) return i - plen + 1;
}
return -1;
}
int main(){
scanf("%d",&n);
while(n--)
{
scanf("%d%d",&slen, &plen);
for(int i = 1; i <= slen; i++)
scanf("%d", &s[i]);
for(int i = 1; i <= plen; i++)
scanf("%d", &p[i]);
get_next();
printf("%d\n", cal_f());
}
return 0;
}