hdu 1711

 

读入优化有3s多。

 1 #include <cstdio>
 2 #include <cctype>
 3 #define maxn 1000010
 4 #define maxm 10010
 5 
 6 int n, m;
 7 int aa[maxn], bb[maxm], f[maxm];
 8 
 9 void gn( int &rt ) {
10     char ch;
11     char opt;
12     while( !isdigit(ch=getchar()) ) opt=ch;
13     rt=ch-'0';
14     while( isdigit(ch=getchar()) )
15         rt=rt*10+ch-'0';
16     if( opt=='-' ) rt=-rt;
17 }
18 
19 void getfail() {
20     f[0] = f[1] = 0;
21     for( int i=1, j; i<m; i++ ) {
22         j = f[i];
23         while( j && bb[i]!=bb[j] ) j=f[j];
24         f[i+1] = bb[i]==bb[j] ? j+1 : 0;
25     }
26 }
27 int kmp() {
28     for( int i=0,j=0; i<n; i++ ) {
29         while( j && aa[i]!=bb[j] ) j=f[j];
30         if( aa[i]==bb[j] ) j++;
31         if( j==m ) return i-m+2;
32     }
33     return -1;
34 }
35 
36 int main() {
37     int T;
38     scanf( "%d", &T );
39     while( T-- ) {
40         scanf( "%d%d", &n, &m );
41         for( int i=0; i<n; i++ )
42             gn(aa[i]);
43         for( int i=0; i<m; i++ )
44             gn(bb[i]);
45         getfail();
46         printf( "%d\n", kmp() );
47     }
48 }
View Code

 

(注意,getfail()中f[i+1] = P[i]==P[j] ? j+1 : 0;)

posted @ 2015-03-10 19:55  idy002  阅读(126)  评论(0编辑  收藏  举报