题意:2个序列A,B,B可以自身全部加减某个数字,问B和A匹配的个数
思路:不管怎样,B序列中相邻2个数之间的差是不变的,然后KMP。
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int N=200005; 4 5 int aa[N],a[N]; 6 int bb[N],b[N]; 7 int n,m; 8 int Next[N]; 9 10 void getnext() 11 { 12 int j, k; 13 j = 0; k = -1; Next[0] = -1; 14 while(j < m) 15 if(k == -1 || b[j] == b[k]) 16 Next[++j] = ++k; 17 else 18 k = Next[k]; 19 20 } 21 22 int KMP_Count() 23 { 24 int ans = 0; 25 int i, j = 0; 26 27 if(n == 1 && m == 1) 28 { 29 if(a[0] == b[0]) 30 return 1; 31 else 32 return 0; 33 } 34 getnext(); 35 for(i = 0; i < n; i++) 36 { 37 while(j > 0 && a[i] != b[j]) 38 j = Next[j]; 39 if(a[i] == b[j]) 40 j++; 41 if(j == m) 42 { 43 ans++; 44 j = Next[j]; 45 } 46 } 47 return ans; 48 } 49 50 int main(){ 51 scanf("%d%d",&n,&m); 52 for(int i=0;i<n;i++) scanf("%d",&aa[i]); 53 for(int i=0;i<m;i++) scanf("%d",&bb[i]); 54 for(int i=0;i<n-1;i++) a[i]=aa[i+1]-aa[i]; 55 for(int i=0;i<m-1;i++) b[i]=bb[i+1]-bb[i]; 56 n--;m--; 57 if(m==0){ 58 cout<<n+1<<endl;return 0; 59 } 60 cout<<KMP_Count()<<endl; 61 }