hdu 2222 Keywords Search AC自动机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/** Sep 8, 2015 8:34:27 PM
* PrjName:hdu2222
* @author Semprathlon
*/
import java.io.*;
import java.util.*;

public class Main {

/**
* @param args
*/
static AC ac = new AC();

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int T = in.nextInt();
while (T-- > 0) {
int n = in.nextInt();
ac.clear();
for (int i = 1; i <= n; i++)
ac.insert(in.next());
ac.build();
out.println(ac.query(in.next()));
}
out.flush();
out.close();
}

}

class AC {
final int maxl = 500010, maxc = 26;
final char fstc = 'a';
int root, L;
int[][] next;
int[] fail, end;
Queue<Integer> que = new LinkedList<Integer>();

AC() {
next = new int[maxl][maxc];
fail = new int[maxl];
end = new int[maxl];
L = 0;
root = newnode();
}

void clear() {
Arrays.fill(fail, 0);
Arrays.fill(end, 0);
L = 0;
root = newnode();
}

int newnode() {
Arrays.fill(next[L], -1);
end[L++] = 0;
return L - 1;
}

void insert(String str) {
int now = root;
for (int i=0;i<str.length();i++) {
char ch=str.charAt(i);
if (next[now][ch - fstc] == -1)
next[now][ch - fstc] = newnode();
now = next[now][ch - fstc];
}
end[now]++;
}

void build() {
que.clear();
fail[root] = root;
for (int i = 0; i < maxc; i++)
if (next[root][i] == -1)
next[root][i] = root;
else {
fail[next[root][i]] = root;
que.add(next[root][i]);
}
while (!que.isEmpty()) {
int now = que.poll();
for (int i = 0; i < maxc; i++)
if (next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else {
fail[next[now][i]] = next[fail[now]][i];
que.add(next[now][i]);
}
}
}

int query(String str) {
int now = root, res = 0;
for (int i=0;i<str.length();i++) {
char ch=str.charAt(i);
now = next[now][ch - fstc];
int tmp = now;
while (tmp != root) {
res += end[tmp];
end[tmp] = 0;
tmp = fail[tmp];
}
}
return res;
}
}

hdu 2222 Keywords Search AC自动机

https://devblog.citruxonve.net/posts/969eea4f/

Author

Semprathlon / Simfae Dean

Posted on

09/08/2015

Updated on

07/19/2023

Licensed under

Comments