AC自动机板子
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6 + 10 ;
int n, m, k;
struct Ans {
int pos, num;
bool operator < ( Ans & b) const {
if ( num == b. num) {
return pos < b. pos;
}
return num > b. num;
}
} ans[ 200 ] ;
namespace AC {
const int maxn = 26 ;
struct Tree {
int fail;
int vis[ maxn] ;
int end;
} AC[ N] ;
int cnt = 0 ;
void clear ( int x) {
memset ( AC[ x] . vis, 0 , sizeof ( AC[ x] . vis) ) ;
AC[ x] . fail = 0 ;
AC[ x] . end = 0 ;
}
void build ( string s, int id) {
int len = s. length ( ) ;
int now = 0 ;
for ( int i = 0 ; i < len; ++ i) {
if ( AC[ now] . vis[ s[ i] - 'a' ] == 0 ) {
AC[ now] . vis[ s[ i] - 'a' ] = ++ cnt;
clear ( cnt) ;
}
now = AC[ now] . vis[ s[ i] - 'a' ] ;
}
AC[ now] . end = id;
}
queue< int > q;
void get_fail ( ) {
for ( int i = 0 ; i < maxn; ++ i) {
if ( AC[ 0 ] . vis[ i] ) {
AC[ AC[ 0 ] . vis[ i] ] . fail = 0 ;
q. push ( AC[ 0 ] . vis[ i] ) ;
}
}
while ( ! q. empty ( ) ) {
int u = q. front ( ) ;
q. pop ( ) ;
for ( int i = 0 ; i < maxn; ++ i) {
if ( AC[ u] . vis[ i] ) {
AC[ AC[ u] . vis[ i] ] . fail = AC[ AC[ u] . fail] . vis[ i] ;
q. push ( AC[ u] . vis[ i] ) ;
} else {
AC[ u] . vis[ i] = AC[ AC[ u] . fail] . vis[ i] ;
}
}
}
}
int AC_Query ( string s) {
int len = s. length ( ) ;
int now = 0 , res = 0 ;
for ( int i = 0 ; i < len; ++ i) {
now = AC[ now] . vis[ s[ i] - 'a' ] ;
for ( int j = now; j && AC[ j] . end != - 1 ; j = AC[ j] . fail) {
ans[ AC[ j] . end] . num++ ;
}
}
return res;
}
void init ( ) {
cnt = 0 ;
clear ( 0 ) ;
}
}
using namespace AC;
string s[ 200 ] ;
int main ( ) {
ios:: sync_with_stdio ( 0 ) ;
while ( cin >> n) {
if ( ! n) break ;
init ( ) ;
for ( int i = 1 ; i <= n; ++ i) {
cin >> s[ i] ;
ans[ i] = { i, 0 } ;
build ( s[ i] , i) ;
}
get_fail ( ) ;
cin >> s[ 0 ] ;
AC_Query ( s[ 0 ] ) ;
sort ( ans + 1 , ans + n + 1 ) ;
cout << ans[ 1 ] . num << endl;
cout << s[ ans[ 1 ] . pos] << endl;
for ( int i = 2 ; i <= n; ++ i) {
if ( ans[ i] . num == ans[ i - 1 ] . num) {
cout << s[ ans[ i] . pos] << endl;
} else break ;
}
}
return 0 ;
}
Trie 树
Trie 图