結果

問題 No.430 文字列検索
ユーザー 沙耶花沙耶花
提出日時 2020-07-12 21:58:07
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 12 ms / 2,000 ms
コード長 1,954 bytes
コンパイル時間 2,147 ms
コンパイル使用メモリ 209,164 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-23 22:39:47
合計ジャッジ時間 3,033 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 12 ms
6,948 KB
testcase_02 AC 5 ms
6,944 KB
testcase_03 AC 5 ms
6,944 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 1 ms
6,940 KB
testcase_06 AC 1 ms
6,940 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 3 ms
6,940 KB
testcase_09 AC 2 ms
6,944 KB
testcase_10 AC 2 ms
6,940 KB
testcase_11 AC 10 ms
6,944 KB
testcase_12 AC 11 ms
6,944 KB
testcase_13 AC 11 ms
6,944 KB
testcase_14 AC 8 ms
6,944 KB
testcase_15 AC 7 ms
6,940 KB
testcase_16 AC 7 ms
6,944 KB
testcase_17 AC 7 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define modulo 1000000007
#define mod(mod_x) ((((long long)mod_x+modulo))%modulo)
#define Inf 1000000000

template <typename T>
struct trie{
	T init_value;
	struct node{
		vector<int> next;
		T v;
		T sum;
		node(int k,T iv){
			next.resize(k,-1);
			v = iv;
			sum = iv;
		}
		
		int link;
	};
	vector<node> _N;
	vector<string> _S;
	int n;
	trie(int k,T iv){
		init_value = iv;
		n = k;
		_N.push_back(node(n,init_value));
	}
	
	void add(string s,T x){
		int now = 0;
		for(int i=0;i<s.size();i++){
			int c = get(s[i]);
			if(_N[now].next[c]==-1){
				_N[now].next[c] = _N.size();
				_N.push_back(node(n,init_value));
			}
			now = _N[now].next[c];
		}
		
		_N[now].v = x;
		_S.push_back(s);
	}
	
	void set_link(){
		_N[0].link = 0;
		queue<int> Q;
		Q.push(0);
		while(Q.size()!=0){
			int now = Q.front();
			Q.pop();
			_N[now].v = func(_N[now].v,_N[_N[now].link].v);
			_N[now].sum = func(_N[now].sum,_N[now].v);
			for(int i=0;i<n;i++){
				int to = _N[now].next[i];
				if(to==-1)continue;
				int x = now;
				while(x!=0){
					x = _N[x].link;
					if(_N[x].next[i]!=-1){
						x = _N[x].next[i];
						break;
					}
				}
				_N[to].link = x;
				_N[to].sum = func(_N[to].sum,_N[now].sum);
				Q.push(to);
			}
		}
	}
	
	T get_value(string S){
		T ret = 0;
		int now = 0;
		for(int i=0;i<S.size();i++){
			int c = get(S[i]);
			if(_N[now].next[c]!=-1){
				now = _N[now].next[c];
				ret = func(ret,_N[now].v);
			}
			else{
				while(now!=0){
					now = _N[now].link;
					if(_N[now].next[c]!=-1){
						now = _N[now].next[c];
						ret = func(ret,_N[now].v);
						break;
					}
				}
			}
		}
		return ret;
	}
	
	int get(char c){
		return c-'A';
	}
	
	T func(T a,T b){
		return a+b;
	}
	
};

int main(){
	
	string S;
	cin>>S;
	int M;
	cin>>M;
	
	trie<int> T(26,0);
	
	for(int i=0;i<M;i++){
		string s;
		cin>>s;
		T.add(s,1);
	}
	
	T.set_link();
	
	cout<<T.get_value(S)<<endl;
	
	
	return 0;
}
0