【CODEFORCES】 D. MUH and Cube Walls

D. MUH and Cube Walls

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.

Horace was the first to finish making his wall. He called his wall an elephant. The wall consists ofwtowers. The bears also finished making their wall but they didn’t give it a name. Their wall consists ofntowers. Horace looked at the bears’ tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment ofwcontiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace’s wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).

Your task is to count the number of segments where Horace can "see an elephant".

Input

The first line contains two integersnandw(1≤n,w≤2·105) — the number of towers in the bears’ and the elephant’s walls correspondingly. The second line containsnintegersai(1≤ai≤109) — the heights of the towers in the bears’ wall. The third line containswintegersbi(1≤bi≤109) — the heights of the towers in the elephant’s wall.

Output

Print the number of segments in the bears’ wall where Horace can "see an elephant".

Sample test(s)

input

13 52 4 5 5 4 3 2 2 2 3 3 2 13 4 4 3 2

output

2

Note

The picture to the left shows Horace’s wall from the sample, the picture to the right shows the bears’ wall. The segments where Horace can "see an elephant" are in gray.

题解:这题是变相KMP,先把A[I] 和 B[I]做处理:令C[I]=A[I+1]-A[I] 、D[I]=B[I+1]-B[I],然后在C D数组上做KMP,,最后输出结果。要注意的是对于w=1的情况要特殊判断。(直接输出n,以为他和每一位都可以相等)#include <cstdio>#include <cstring>#include <iostream>using namespace std;int a[200005],b[200005],next[200005],n,w;long long c[200005],d[200005];int main(){int i=2,k=0,ans=0;scanf("%d%d",&n,&w);if (w==1){printf("%d\n",n);return 0;}for (i=1;i<=n;i++) scanf("%d",&a[i]);for (i=1;i<=w;i++) scanf("%d",&b[i]);memset(c,-1,sizeof(c));for (i=1;i<=n-1;i++) c[i]=a[i+1]-a[i];for (i=1;i<=w-1;i++) d[i]=b[i+1]-b[i];//KMP to dmemset(next,0,sizeof(next));next[1]=0;i=2; k=0;// next[i]while (i<=w-1){if (d[k+1]==d[i]){next[i]=next[i-1]+1;i++;k=next[i-1];}else{k=next[k];if (k==0){next[i]=0;i++;}}}// compare c di=1;k=1;while (i<=n-1){while (c[i]==d[k] && i<=n-1 && k<=w-1){i++; k++;}if (k==1) i++;else if (k==w){ans++;k=next[k-1]+1;}elsek=next[k-1]+1;}printf("%d\n",ans);return 0;}

如果你在以的话,别人就会知道你害怕被说,他们就会加倍地说你,

【CODEFORCES】 D. MUH and Cube Walls

相关文章:

你感兴趣的文章:

标签云: