結果

問題 No.430 文字列検索
ユーザー kazumakazuma
提出日時 2017-07-25 23:12:35
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 36 ms / 2,000 ms
コード長 1,893 bytes
コンパイル時間 2,445 ms
コンパイル使用メモリ 205,732 KB
実行使用メモリ 27,004 KB
最終ジャッジ日時 2024-04-17 23:37:37
合計ジャッジ時間 3,374 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 36 ms
27,004 KB
testcase_02 AC 10 ms
9,728 KB
testcase_03 AC 10 ms
9,600 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 1 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 2 ms
5,376 KB
testcase_08 AC 3 ms
5,376 KB
testcase_09 AC 2 ms
5,376 KB
testcase_10 AC 2 ms
5,376 KB
testcase_11 AC 27 ms
18,944 KB
testcase_12 AC 30 ms
21,600 KB
testcase_13 AC 29 ms
21,484 KB
testcase_14 AC 24 ms
16,896 KB
testcase_15 AC 16 ms
12,928 KB
testcase_16 AC 15 ms
12,928 KB
testcase_17 AC 14 ms
12,800 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

class Aho_Corasick {
	struct node {
		node *no;
		vector<node*> next;
		vector<int> matched;
		node() : no(nullptr), next(128, nullptr) {}
		~node() { for (auto ite : next) if (ite != nullptr) delete ite; }
	};
	vector<int> unite(const vector<int>& a, const vector<int>& b) {
		vector<int> res;
		set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res));
		return res;
	}
	int K;
	node *root;
public:
	Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) {
		node *now;
		root->no = root;
		for (int i = 0; i < K; i++) {
			auto &T = Ts[i];
			now = root;
			for (auto c : T) {
				if (now->next[c] == nullptr) {
					now->next[c] = new node;
				}
				now = now->next[c];
			}
			now->matched.push_back(i);
		}
		queue<node*> q;
		for (int i = 0; i < 128; i++) {
			if (root->next[i] == nullptr) {
				root->next[i] = root;
			}
			else {
				root->next[i]->no = root;
				q.push(root->next[i]);
			}
		}
		while (!q.empty()) {
			now = q.front(); q.pop();
			for (int i = 0; i < 128; i++) {
				if (now->next[i] != nullptr) {
					node *nx = now->no;
					while (nx->next[i] == nullptr) {
						nx = nx->no;
					}
					now->next[i]->no = nx->next[i];
					now->next[i]->matched = unite(now->next[i]->matched, nx->next[i]->matched);
					q.push(now->next[i]);
				}
			}
		}
	}
	vector<int> count(const string& S) {
		vector<int> res(K);
		node *now = root;
		for (auto c : S) {
			while (now->next[c] == nullptr) {
				now = now->no;
			}
			now = now->next[c];
			for (auto k : now->matched) {
				res[k]++;
			}
		}
		return res;
	}
};

int main()
{
	string S;
	int M;
	cin >> S >> M;
	vector<string> C(M);
	for (int i = 0; i < M; i++) {
		cin >> C[i];
	}
	Aho_Corasick aho(C);
	auto cnt = aho.count(S);
	ll res = 0;
	for (auto t : cnt) {
		res += t;
	}
	cout << res << endl;
	return 0;
}
0