Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2330 Accepted Submission(s): 874
#include <cstdio> #include <iostream> #include <cstring> using namespace std; const int N = 1000002; int Next[N]; int S[N], T[N]; int slen, tlen;//注意每次一定要计算长度 int n,m,p; void getNext() { int j, k; j = 0; k = -1; Next[0] = -1; while(j < tlen) if(k == -1 || T[j] == T[k]) Next[++j] = ++k; else k = Next[k]; } int KMP_Count() { int ans = 0; int i, j = 0; if(slen == 1 && tlen == 1) { if(S[0] == T[0]) return 1; else return 0; } getNext(); for(int k=0;k<p;k++){ j=0; for(i = k; i < slen; i=i+p) { while(j>=0 && S[i] != T[j]) j = Next[j]; if(j==-1||S[i] == T[j]) j++; if(j == tlen) { ans++; j = Next[j]; } } } return ans; } int main() { int TT,Case=0; scanf("%d",&TT); while(TT--) { Case++; scanf("%d%d%d",&n,&m,&p); for(int i=0;i<n;i++)scanf("%d",&S[i]); for(int i=0;i<m;i++)scanf("%d",&T[i]); slen=n; tlen=m;; printf("Case #%d: %d\n",Case,KMP_Count()); } return 0; } /*10 3 1 5 1 1 1 1 Case #1: 1 */
原文:http://www.cnblogs.com/a249189046/p/7476476.html