图片来自点击打开链接
Sample Input
1 5 she he say shr her yasherhs
Sample Output
3
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new Task().solve() ;
}
}
class Task{
InputReader in = new InputReader(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
AhoCorasick ac = new AhoCorasick() ;
void solve(){
int t = in.nextInt() ;
while(t-- > 0){
ac.clear() ;
int n = in.nextInt() ;
while(n-- > 0){
ac.add(in.next()) ;
}
ac.build() ;
out.println(ac.query(in.next())) ;
}
out.flush() ;
}
}
class AhoCorasick{
final int NODE_SIZE = 500008 ;
final int ALPHA_SIZE = 26 ;
final int NULL = 0 ;
int[][] next = new int[NODE_SIZE][ALPHA_SIZE] ;
int[] fail = new int[NODE_SIZE] ;
int[] cnt = new int[NODE_SIZE] ;
int root ;
int total ;
void clear(){
total = 0 ;
root = newNode() ;
}
int newNode(){
cnt[total] = 0 ;
Arrays.fill(next[total] , NULL) ;
return total++ ;
}
void add(String word){
int now = root ;
for(char c : word.toCharArray()){
int son = c - 'a' ;
if(next[now][son] == NULL) next[now][son] = newNode() ;
now = next[now][son] ;
}
cnt[now]++ ;
}
void build(){
Queue<Integer> q = new LinkedList<Integer>() ;
for(int son = 0 ; son < ALPHA_SIZE ; son++){
if(next[root][son] == NULL) next[root][son] = root ;
else{
fail[next[root][son]] = root;
q.add(next[root][son]) ;
}
}
while(! q.isEmpty()){
int u = q.poll() ;
for(int son = 0 ; son < ALPHA_SIZE ; son++){
if(next[u][son] == NULL) next[u][son] = next[fail[u]][son] ;
else{
fail[next[u][son]] = next[fail[u]][son] ;
q.add(next[u][son]) ;
}
}
}
}
int query(String text){
int res = 0 ;
int now = root ;
for(char c : text.toCharArray()){
now = next[now][c-'a'] ;
int u = now ;
while(u != root && cnt[u] > 0){
res += cnt[u] ;
cnt[u] = 0 ;
u = fail[u] ;
}
}
return res ;
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = new StringTokenizer("");
}
private void eat(String s) {
tokenizer = new StringTokenizer(s);
}
public String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}