結果

問題 No.430 文字列検索
ユーザー 👑 はまやんはまやんはまやんはまやん
提出日時 2017-02-23 04:03:42
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 14 ms / 2,000 ms
コード長 1,833 bytes
コンパイル時間 2,116 ms
コンパイル使用メモリ 184,104 KB
実行使用メモリ 6,724 KB
最終ジャッジ日時 2023-08-30 03:29:09
合計ジャッジ時間 3,205 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 14 ms
6,724 KB
testcase_02 AC 7 ms
4,376 KB
testcase_03 AC 7 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 3 ms
4,376 KB
testcase_09 AC 3 ms
4,380 KB
testcase_10 AC 2 ms
4,376 KB
testcase_11 AC 13 ms
5,712 KB
testcase_12 AC 13 ms
6,008 KB
testcase_13 AC 13 ms
5,972 KB
testcase_14 AC 11 ms
5,444 KB
testcase_15 AC 9 ms
5,120 KB
testcase_16 AC 9 ms
5,124 KB
testcase_17 AC 9 ms
5,108 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)




const int NUMC = 26;
class Trie {
public:
	vector<vector<int> > V;
	int find(string s) {
		int cur = 0;
		for(char it : s) if ((cur = V[cur][it + 1]) == 0) return -1;
		return cur;
	}
	void create(vector<string> S) { // 0 is for backtrack
		V.clear();
		V.push_back(vector<int>(NUMC + 1));
		sort(S.begin(), S.end());
		for(string it: S) {
			int cur = 0;
			for(char c: it) {
				if (V[cur][c + 1] == 0) V.push_back(vector<int>(NUMC + 1)), V[cur][c + 1] = V.size() - 1;
				cur = V[cur][c + 1];
			}
		}
	}
};


class ACmatch_num {
public:
	Trie t;
	vector<int> acc;
	int ma;
	void create(vector<string> S) {
		int i;
		ma = S.size();
		t.create(S);
		acc.clear();
		acc.resize(t.V.size());
		rep(i, 0, S.size()) acc[t.find(S[i])]++;
		queue<int> Q;
		rep(i, 0, NUMC) if (t.V[0][i + 1]) t.V[t.V[0][i + 1]][0] = 0, Q.push(t.V[0][i + 1]);

		while (!Q.empty()) {
			int k = Q.front(); Q.pop();
			rep(i, 0, NUMC) if (t.V[k][i + 1]) {
				Q.push(t.V[k][i + 1]);
				int pre = t.V[k][0];
				while (pre && t.V[pre][i + 1] == 0) pre = t.V[pre][0];
				t.V[t.V[k][i + 1]][0] = t.V[pre][i + 1];
				acc[t.V[k][i + 1]] += acc[t.V[pre][i + 1]];
			}
		}
	}
	int match(string S) {
		int R = 0;
		int cur = 0;
		for(char it : S) {
			while (cur && t.V[cur][it + 1] == 0) cur = t.V[cur][0];
			cur = t.V[cur][it + 1];
			R += acc[cur];
		}
		return R;
	}
};
//-----------------------------------------------------------------
string S;
int M;
vector<string> C;
ACmatch_num ac;
//-----------------------------------------------------------------
int main() {
	cin >> S >> M;
	rep(i, 0, M) {
		string s;
		cin >> s;
		rep(j, 0, s.length()) s[j] -= 'A';
		C.push_back(s);
	}
	rep(i, 0, S.length()) S[i] -= 'A';

	ac.create(C);
	cout << ac.match(S) << endl;
}
0