結果

問題 No.430 文字列検索
ユーザー 37zigen37zigen
提出日時 2016-10-28 14:40:29
言語 Java21
(openjdk 21)
結果
RE  
実行時間 -
コード長 2,205 bytes
コンパイル時間 3,792 ms
コンパイル使用メモリ 80,004 KB
実行使用メモリ 56,236 KB
最終ジャッジ日時 2024-05-03 07:14:36
合計ジャッジ時間 7,719 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 137 ms
40,984 KB
testcase_01 RE -
testcase_02 RE -
testcase_03 RE -
testcase_04 RE -
testcase_05 RE -
testcase_06 RE -
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 RE -
testcase_11 RE -
testcase_12 RE -
testcase_13 RE -
testcase_14 RE -
testcase_15 RE -
testcase_16 RE -
testcase_17 RE -
権限があれば一括ダウンロードができます

ソースコード

diff #

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 p = 0;
			int ptn = 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 ch) {
				if (p == 0)
					child = new Node[1];
				else if (p + 1 > child.length)
					Arrays.copyOf(child, child.length * 2);
				int zind = Integer.bitCount(ptn << 31 - (c - 'a'));
				System.arraycopy(child, zind, child, zind + 1, p - zind);
				ptn |= 1 << (c - 'a');
				child[zind] = ch;
				++p;
			}
		}

		void buildFailure() {
			Queue<Node> q = new ArrayDeque<>();
			q.add(root);
			while (!q.isEmpty()) {
				Node cur = q.poll();
				outer: for (int i = 0; i < cur.p; ++i) {
					for (Node to = cur.fail; to != null; to = to.fail) {
						Node next = to.search(cur.child[i].c);
						if (next != null) {
							cur.child[i].hit += next.hit;
							cur.child[i].fail = next;
							continue outer;
						}
					}
					cur.child[i].fail = root;
				}
			}
		}

		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;
		}

		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;
		}
	}
}
 
0