这个就是不断的间隔选取新的数组,然后来kmp,暑期集训学的一发kmp,但是忘了,不做真的又忘了,又花了一点时间学了一发
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MaxN = 1e6;
int T , n , m , p , ans , cas = 0;
int a[MaxN + 5] , b[MaxN + 5] ,c[MaxN + 5];
int nxt[MaxN + 5];
void Init()
{
scanf("%d %d %d", &n , &m , &p);
for(int i = 1 ; i <= n ; i++) scanf("%d",&a[i]);
for(int i = 1 ; i <= m ; i++) scanf("%d",&b[i]);
memset(nxt , 0 , sizeof(nxt));
ans = 0;
}
void Kmp(int a[] , int b[] , int n , int m)//a目的串数目,b匹配串,n目的串数目,m匹配串数目
{
if(m > n) return ;
int pos = 0 ; nxt[1] = 0;
for(int i = 2 ; i <= m ; i++){
while(pos > 0 && b[pos + 1] != b[i]) pos = nxt[pos];
if(b[pos + 1] == b[i]) pos = pos + 1;
nxt[i] = pos;
}
pos = 0;
for(int i = 1 ; i <= n ; i++){
while(pos > 0 && a[i] != b[pos + 1]) pos = nxt[pos];
if(a[i] == b[pos + 1]) pos = pos + 1;
if(pos == m) ans++ ,pos = nxt[pos];
}
}
void Solve()
{
int tail , tot;
for(int head = 1 ; head <= p ; head++){
tot = 0, tail = head;
while(tail <= n){
c[++tot] = a[tail];
tail += p;
}
Kmp(c , b , tot , m);//c,目的串,b模式串,tot目的串数,m匹配串数目
}
printf("Case #%d: %d\n",++cas , ans);
}
int main()
{
scanf("%d",&T);
for(int cas = 1 ; cas <= T ; cas++){
Init();
Solve();
}
}