AcWing 1282. Java版本AC自动机 yxc思路
原题链接
中等
作者:
Karma
,
2021-03-16 19:34:38
,
所有人可见
,
阅读 416
import java.io.*;
class Main{
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int nextInt()throws Exception{
in.nextToken();
return (int)in.nval;
}
static String next()throws Exception{
in.nextToken();
return in.sval;
}
static final int S = 55;
static int n, idx;
static int[][] son;
static int[] cnt, qu, ne;
static void insert(String s){
int p = 0;
for(int i=0; i<s.length(); i++){
char cur = s.charAt(i);
int t = cur - 'a';
if(son[p][t]==0) son[p][t] = ++idx;
p = son[p][t];
}
cnt[p]++;
}
static void build(){
int tt, hh;
tt = -1; hh = 0;
for(int i=0; i<26; i++) if(son[0][i]>0) qu[++tt] = son[0][i];
while(tt>=hh){
int t = qu[hh++];
for(int i=0; i<26; i++){
int u = son[t][i];
if(u==0) continue;
int j = ne[t];
while(j!=0&&son[j][i]==0) j = ne[j];
if(son[j][i]>0) j = son[j][i];
ne[u] = j;
qu[++tt] = u;
}
}
}
public static void main(String[] args) throws Exception{
int T = nextInt();
while(T-->0){
n = nextInt();
son = new int[n*S][26];
cnt = new int[n*S];
qu = new int[n*S];
ne = new int[n*S];
idx = 0;
for(int i=0; i<n; i++){
String s = next();
insert(s);
}
build();
int res = 0;
String m = next();
for(int i=0, j=0; i<m.length(); i++){
int t = m.charAt(i) - 'a';
while(j!=0&&son[j][t]==0) j = ne[j];
if(son[j][t]!=0) j = son[j][t];
int b = j;
while(b!=0){
res += cnt[b];
cnt[b] = 0;
b = ne[b];
}
}
System.out.println(res);
}
}
}