結果
問題 | No.430 文字列検索 |
ユーザー | 37zigen |
提出日時 | 2016-10-28 14:08:09 |
言語 | Java21 (openjdk 21) |
結果 |
AC
|
実行時間 | 281 ms / 2,000 ms |
コード長 | 2,221 bytes |
コンパイル時間 | 3,861 ms |
コンパイル使用メモリ | 80,184 KB |
実行使用メモリ | 47,344 KB |
最終ジャッジ日時 | 2024-05-03 07:14:19 |
合計ジャッジ時間 | 8,711 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 140 ms
41,496 KB |
testcase_01 | AC | 269 ms
46,656 KB |
testcase_02 | AC | 258 ms
44,400 KB |
testcase_03 | AC | 254 ms
44,600 KB |
testcase_04 | AC | 136 ms
41,416 KB |
testcase_05 | AC | 135 ms
41,088 KB |
testcase_06 | AC | 135 ms
41,384 KB |
testcase_07 | AC | 137 ms
41,584 KB |
testcase_08 | AC | 190 ms
41,948 KB |
testcase_09 | AC | 150 ms
41,216 KB |
testcase_10 | AC | 157 ms
41,744 KB |
testcase_11 | AC | 268 ms
47,036 KB |
testcase_12 | AC | 281 ms
47,268 KB |
testcase_13 | AC | 277 ms
47,344 KB |
testcase_14 | AC | 273 ms
46,860 KB |
testcase_15 | AC | 274 ms
46,060 KB |
testcase_16 | AC | 262 ms
45,968 KB |
testcase_17 | AC | 268 ms
46,056 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 hit = 0; Node fail; int ptn; int p = 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 appendChild(Node n) { if (p == 0) child = new Node[1]; else if (p + 1 > child.length) child = Arrays.copyOf(child, 2 * child.length); int z = n.c - 'a'; int zind = Integer.bitCount(ptn << 31 - z); System.arraycopy(child, zind, child, zind + 1, p - zind); ptn |= 1 << z; child[zind] = n; ++p; } } void buildFailure() { root.fail = null; Queue<Node> q = new ArrayDeque<>(); q.add(root); while (!q.isEmpty()) { Node cur = q.poll(); inner: 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 inner; } } ch.fail = root; } } } void add(char[] s) { Node cur = root; Node pre = null; for (char c : s) { pre = cur; cur = pre.search(c); if (cur == null) { cur = new Node(gen++, c); pre.appendChild(cur); } } ++cur.hit; } int countHit(char[] s) { Node cur = root; int hit=0; outer:for(char c:s){ for(;cur!=null;cur=cur.fail){ Node next=cur.search(c); if(next!=null) { hit+=next.hit; cur=next; continue outer; } } cur=root; } return hit; } } }