HDU 1711 Number Sequence(模板题)
#include <cstdio> const int MAXN = 1000010; const int MAXL = 10010; int N, M; int textS[MAXN]; int tarS[MAXL]; int next[MAXL]; void GetNextVal( int* s, int* nextval, int len ) { int i = 0, j = -1; nextval[0] = -1; while ( i < len ) { if ( j == -1 || s[i] == s[j] ) { ++i, ++j; nextval[i] = j; } else j = nextval[j]; } return; } int KMP( int *t, int lent, int *s, int lens ) { GetNextVal( t, next, lent ); int i = 0, j = 0; while ( j < lens ) { if ( i == -1 || s[j] == t[i] ) { ++i, ++j; if ( i == lent ) return j; } else i = next[i]; } return -1; } int main() { int T; scanf( "%d", &T ); while ( T-- ) { scanf( "%d%d", &N, &M ); for ( int i = 0; i < N; ++i ) scanf( "%d", &textS[i] ); for ( int i = 0; i < M; ++i ) scanf( "%d", &tarS[i] ); int ans = KMP( tarS, M, textS, N ); if ( ans < 0 ) printf( "%d\n", ans ); else printf("%d\n", ans - M + 1 ); } return 0; }