HDU1711/HDU1686 KMP
1 #include <bits/stdc++.h> 2 using namespace std; 3 int T,n,m; 4 int a[1000005],b[10005]; 5 int nxt[10005]; 6 7 8 void getnxt(){ 9 int j = 0,k = -1; 10 while(j < m){ 11 if (k == -1 || b[j] == b[k]){ 12 if (b[++j] == b[++k]){ 13 nxt[j] = nxt[k]; 14 }else{ 15 nxt[j] = k; 16 } 17 }else{ 18 k = nxt[k]; 19 } 20 } 21 } 22 23 int kmp(){ 24 getnxt(); 25 int i,j = i= 0; 26 while(i < n && j < m){ 27 if (j == -1 || a[i] == b[j]){ 28 i++; 29 j++; 30 }else{ 31 j = nxt[j]; 32 } 33 } 34 if (j == m) return i-j + 1; 35 else return -1; 36 } 37 38 int main(){ 39 scanf("%d",&T); 40 while(T--){ 41 memset(nxt,-1,sizeof(nxt)); 42 scanf("%d%d",&n,&m); 43 for (int i = 0;i < n;++i) scanf("%d",a+i); 44 for (int i = 0;i < m;++i) scanf("%d",b+i); 45 46 printf("%d\n",kmp()); 47 } 48 return 0; 49 }
上面是1711,下面是1686
#include <bits/stdc++.h> using namespace std; int nxt[10010]; char a[1000005]; char b[10010]; int n,m,T; void getnext(){ memset(nxt,-1,sizeof(nxt)); int j = -1; nxt[0] = -1; int i = 0; while(i < m){ while(j != -1 && b[j] != b[i]) j = nxt[j]; i++;j++; nxt[i] = j; } } int kmp() { int cnt = 0; int i,j = i = 0; while(i < n){ while(j != -1 && b[j] != a[i]) j = nxt[j]; i++;j++; if (j >= m){ cnt++; j = nxt[j]; } } return cnt; } int main() { scanf("%d",&T); while(T--){ scanf("%s",b); m = strlen(b); scanf("%s",a); n = strlen(a); getnext(); printf("%d\n",kmp()); } }