codeforces #269 div2 D题(KMP)

2014-12-16 17:15:56

思路:考虑数与数间的关系,那么我们提取关系:数与前一个数的差,那么我们提取出n-1、w-1对关系,然后用w-1去匹配n-1即可,用kmp

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <vector>
 6 #include <map>
 7 #include <set>
 8 #include <stack>
 9 #include <queue>
10 #include <iostream>
11 #include <algorithm>
12 using namespace std;
13 #define lp (p << 1)
14 #define rp (p << 1|1)
15 #define getmid(l,r) (l + (r - l) / 2)
16 #define MP(a,b) make_pair(a,b)
17 typedef long long ll;
18 typedef unsigned long long ull;
19 const int INF = 1 << 30;
20 const int maxn = 200010;
21 
22 int n,w;
23 int a[maxn],b[maxn],P[maxn];
24 
25 int main(){
26     scanf("%d%d",&n,&w);
27     for(int i = 1; i <= n; ++i) scanf("%d",a + i);
28     for(int i = 1; i <= w; ++i) scanf("%d",b + i);
29     if(w == 1){
30         printf("%d\n",n);
31         return 0;
32     }
33     for(int i = 1; i < n; ++i) a[i] = a[i + 1] - a[i];
34     for(int i = 1; i < w; ++i) b[i] = b[i + 1] - b[i];
35     int j = 0;
36     P[1] = 0;
37     for(int i = 2; i < w; ++i){
38         while(j > 0 && b[j + 1] != b[i]) j = P[j];
39         if(b[j + 1] == b[i]) j++;
40         P[i] = j;
41     }
42     j = 0;
43     int ans = 0;
44     for(int i = 1; i < n; ++i){
45         while(j > 0 && b[j + 1] != a[i]) j = P[j];
46         if(b[j + 1] == a[i]) j++;
47         if(j == w - 1) ++ans,j = P[j];
48     }
49     printf("%d\n",ans);
50     return 0;
51 }

 

posted @ 2014-12-16 17:18  Naturain  阅读(119)  评论(0编辑  收藏  举报