Description
Input
Output
Sample Input
6 3
1 2 3 4 5 6
1 2 3
Sample Output
4
做法:朴素的做法。。读入后做一次差分,然后kmp
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int a[1000005],b[1000005],p[1000005],n,m,next[1000005],ans;
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
scanf("%d", &p[i]);
a[i - 1] = p[i] - p[i - 1];
}
for (int i = 1; i <= m; i++)
{
scanf("%d", &p[i]);
b[i - 1] = p[i] - p[i - 1];
}
int j = 0;
for (int i = 2; i < m; i++)
{
while (j > 0 && b[j + 1] != b[i]) j = next[j];
if (b[j + 1] == b[i]) j += 1;
next[i] = j;
}
j = 0;
for (int i = 1; i < n; i++)
{
while (j > 0 && b[j + 1] != a[i]) j = next[j];
if (b[j + 1] == a[i]) j += 1;
if (j == m - 1)
{
ans++;
j = next[j];
}
}
printf("%d", ans);
}