結果
問題 | No.430 文字列検索 |
ユーザー | 37zigen |
提出日時 | 2016-10-28 15:14:30 |
言語 | Java21 (openjdk 21) |
結果 |
AC
|
実行時間 | 246 ms / 2,000 ms |
コード長 | 2,240 bytes |
コンパイル時間 | 3,279 ms |
コンパイル使用メモリ | 87,260 KB |
実行使用メモリ | 47,308 KB |
最終ジャッジ日時 | 2024-05-03 07:14:57 |
合計ジャッジ時間 | 7,370 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 117 ms
41,436 KB |
testcase_01 | AC | 246 ms
47,308 KB |
testcase_02 | AC | 238 ms
45,272 KB |
testcase_03 | AC | 208 ms
44,728 KB |
testcase_04 | AC | 104 ms
41,168 KB |
testcase_05 | AC | 104 ms
41,420 KB |
testcase_06 | AC | 121 ms
41,360 KB |
testcase_07 | AC | 121 ms
41,384 KB |
testcase_08 | AC | 177 ms
41,604 KB |
testcase_09 | AC | 131 ms
41,832 KB |
testcase_10 | AC | 147 ms
41,804 KB |
testcase_11 | AC | 230 ms
46,292 KB |
testcase_12 | AC | 243 ms
46,616 KB |
testcase_13 | AC | 243 ms
47,168 KB |
testcase_14 | AC | 244 ms
46,016 KB |
testcase_15 | AC | 226 ms
46,812 KB |
testcase_16 | AC | 232 ms
46,632 KB |
testcase_17 | AC | 234 ms
46,068 KB |
ソースコード
package yukicoder; import java.util.*; public class Q430 { public static void main(String[] args) { new Q430().run(); } void run() { solver(); } void solver() { TrieByList trie=new TrieByList(); Scanner sc=new Scanner(System.in); char[] s=sc.next().toCharArray(); int m=sc.nextInt(); while(m-->0){ trie.add(sc.next().toCharArray()); } trie.buildFailure(); System.out.println(trie.countHit(s)); } class TrieByList { Node root = new Node(0, (char) -1); int gen = 1; class Node { int id; char c; Node[] child=null; int ptn=0; int p=0; Node fail; int hit = 0; public Node(int id, char c) { this.id = id; this.c = c; } Node search(char c) { if (ptn << 31 - (c - 'a') < 0) return child[Integer.bitCount(ptn << 31 - (c - 'a')) - 1]; else return null; } void append(Node n) { if (p == 0) child = new Node[1]; else if (p + 1 > child.length) { child = Arrays.copyOf(child, child.length * 2); } int zind = Integer.bitCount(ptn << 31 - (n.c - 'a')); System.arraycopy(child, zind, child, zind + 1, p - zind); child[zind] = n; ptn |= 1 << (n.c - 'a'); ++p; } } void add(char[] s) { Node pre = null; Node cur = root; for (char c : s) { pre = cur; cur = pre.search(c); if (cur == null) { cur = new Node(gen++, c); pre.append(cur); } } ++cur.hit; } void buildFailure() { root.fail = null; Queue<Node> q = new ArrayDeque<>(); q.add(root); while (!q.isEmpty()) { Node cur = q.poll(); outer: for (int i = 0; i < cur.p; ++i) { Node ch = cur.child[i]; q.add(ch); for (Node to = cur.fail; to != null; to = to.fail) { Node next = to.search(ch.c); if (next != null) { ch.fail = next; ch.hit += next.hit; continue outer; } } ch.fail = root; } } } int countHit(char[] s) { int hit = 0; Node cur = root; outer:for (char c : s) { for (Node to = cur; to != null; to = to.fail) { Node next = to.search(c); if (next != null) { hit += next.hit; cur = next; continue outer; } } cur = root; } return hit; } } }