题目
解题思路
代码
#include <cstdio>
#include <cstring>
#define ll long long
#define lw 200560490131ll
#define xxy 999983
#define N 1000010
#define rep(i,x,y) for (register int i=x;i<=y;i++)
using namespace std;
ll e[ N] = { 0 , 1 } , h[ N* 2 ] , c[ N] , t;
int a[ N] , b[ N] , next[ N] , pre, n, m, j; char s[ N] ;
int hash ( ll k, int n) {
ll y= k% xxy;
while ( h[ y] ) {
if ( h[ y] == k) { int x= c[ y] ; c[ y] = n; return x; }
y= ( y+ 1 ) % 1000000 ;
}
h[ y] = k; c[ y] = n; return 0 ;
}
int main ( ) {
rep ( i, 2 , 1000000 ) e[ i] = e[ i- 1 ] * 27 % lw;
while ( scanf ( "%s" , s+ 1 ) , s[ 1 ] != '$' ) {
n++ ; t= 0 ; rep ( i, 1 , strlen ( s+ 1 ) ) t= ( t+ ( s[ i] - 96 ) * e[ i] ) % lw;
pre= hash ( t, n) ; a[ n] = ( pre== 0 ) ? pre: n- pre;
}
scanf ( "\n" ) ; memset ( c, 0 , sizeof ( c) ) , memset ( h, 0 , sizeof ( h) ) ;
while ( scanf ( "%s" , s+ 1 ) , s[ 1 ] != '$' ) {
m++ ; t= 0 ; rep ( i, 1 , strlen ( s+ 1 ) ) t= ( t+ ( s[ i] - 96 ) * e[ i] ) % lw;
pre= hash ( t, m) ; b[ m] = ( pre== 0 ) ? pre: m- pre;
}
rep ( i, 2 , m) {
while ( j&& b[ j] != b[ j+ 1 ] ) j= next[ j] ;
if ( b[ j] == b[ j+ 1 ] ) j++ ;
next[ i] = j;
}
rep ( i, 1 , n) {
while ( j&& ! ( b[ j+ 1 ] == a[ i] || ( b[ j+ 1 ] == 0 && a[ i] > j) ) ) j= next[ j] ;
if ( b[ j+ 1 ] == a[ i] || ( b[ j+ 1 ] == 0 && a[ i] > j) ) j++ ;
if ( j== m) return 0 & printf ( "%d\n" , i- m+ 1 ) ;
}
}