传说中的KMP算法,适用于寻找子串问题,其核心思路是先将子串进行自我匹配,构建出一个next数组。当寻找子串时匹配失败,就可以回到下标为当前位置的next数组里继续开始匹配,避免了每次都得从头再来的麻烦,以此来节省时间。
Run Time: 0.14sec
Run Memory: 660KB
Code length: 882Bytes
SubmitTime: 2011-11-03 13:34:35
// Problem#: 1282
// Submission#: 940275
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
long n, m;
int code[ 60001 ], next[ 60001 ], gate;
long i, j, k;
while ( cin >> n ) {
for ( i = 1; i <= n; i++ )
scanf( "%d", &code[ i ] );
next[ 1 ] = 0;
j = 0;
for ( i = 2; i <= n; i++ ) {
j = code[ j + 1 ] == code[ i ] ? j + 1: 0;
next[ i ] = j;
}
scanf( "%ld", &m );
j = 0;
for ( i = 1; i <= m; i++ ) {
scanf( "%d", &gate );
if ( j != n ) {
j = code[ j + 1 ] == gate ? j + 1: next[ j ];
if ( j == n )
k = i - j;
}
}
j == n ? cout << k << endl: cout << "no solution\n";
}
return 0;
}