Kmp has been doing this for the past few days. Today, we have A question about hdu 1711, which is A simple kmp template question;
The core of kmp is the next array, which has been reading Yan Weimin's Data Structure textbooks over the past few days.
Next [j] = {
0, j = 1,
Max {k | 1 <k <j, and P1P2 '...... Pk-1 = Pj-k + 1 ...... Pj-1 },
1,
}
Next [j] indicates the length of the longest first and last compound substring from 1 to K-1 + 1, that is, when the number [j] of the mode string does not match the number [I] of the text string, the primary string pointer I does not need to be traced back, however, only the j of the mode string is next [j]. If the text string is S and the mode string is P, the next S [I] is compared with P [next [j, j should be traced back to next [j];
#include<stdio.h> #include<iostream> #include<cmath> #include<algorithm> #include<string> #include<vector> #include<cstring> using namespace std; const int N=1000003; int next[N]; int a[N],b[N]; void getNext( int str[], int pos ,int len) { if(next == NULL || str == NULL ) return ; next[0] = -1; int i=pos,j=-1; while( i < len) { if(j == -1 || str[i] == str[j]) { i++; j++; next[i] = j;// } else { j=next[j]; } } } int main() { //freopen("1.txt","r",stdin); //freopen("2.txt","w",stdout); int T; scanf("%d",&T); while(T--){ int n,m; scanf("%d%d",&n,&m); for(int i=0;i<n;i++){ scanf("%d",&a[i]); } for(int i=0;i<m;i++) { scanf("%d",&b[i]); } getNext(b,0,m); int i=0,j=0; while(i<n && j<m ){ if(j == -1 || a[i] == b[j]){ i++; j++; } else{ j=next[j]; } } if(j==m){ printf("%d\n",i-m+1); }else{ printf("-1\n"); } } return 0; }