HDU 1171 Number Sequence KMP 第二道
这是我水的第二道KMP题目。。。 哈哈 用了输入外挂187MS水过
#include<stdio.h> int num1[1000005],num2[10005],next[10005],n,m; void getnext( ) { int i = 0,j = -1; next[0] = -1; while( i < m ) { if( j == -1 || num2[i] == num2[j] ) ++i,++j,next[i] = j; else j = next[j]; } } int KMP( ) { int i = 0, j = 0; while( i < n && j < m ) if( j == -1 || num1[i] == num2[j] ) ++i,++j; else j = next[j]; if( j == m )//这里错了j = m return i - j + 1; else return -1; } inline bool read(int &num) { char in;bool IsN=false; in=getchar(); if(in==EOF) return false; while(in!='-'&&(in<'0'||in>'9')) in=getchar(); if(in=='-'){ IsN=true;num=0;} else num=in-'0'; while(in=getchar(),in>='0'&&in<='9') num*=10,num+=in-'0'; if(IsN) num=-num; return true; } int main( ) { int t; scanf( "%d",&t ); while( t-- ) { read( n ); read( m ); for( int i = 0; i < n; ++i ) read( num1[i] ); for( int j = 0; j < m; ++j ) read( num2[j] ); getnext( ); printf( "%d\n",KMP( ) ); } return 0; }
本人还是新手 ,转载请注明来自Lvsi‘s home