結果
| 問題 |
No.430 文字列検索
|
| コンテスト | |
| ユーザー |
沙耶花
|
| 提出日時 | 2020-08-26 15:08:27 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 16 ms / 2,000 ms |
| コード長 | 2,267 bytes |
| コンパイル時間 | 2,515 ms |
| コンパイル使用メモリ | 203,796 KB |
| 最終ジャッジ日時 | 2025-01-13 14:59:29 |
|
ジャッジサーバーID (参考情報) |
judge3 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 14 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
#define modulo 998244353
#define mod(mod_x) ((((long long)mod_x+modulo))%modulo)
#define Inf 1000000000000
template <typename T>
struct trie{
T init_value;
struct node{
vector<int> next;
T v;
T sum;
int depth;
node(int wordSize,T iv,int d){
next.resize(wordSize,-1);
v = iv;
sum = iv;
depth = d;
}
int link=-1;
};
vector<node> nodes;
int wordSize;
trie(int sz,T iv){
init_value = iv;
wordSize = sz;
nodes.push_back(node(wordSize,init_value,0));
}
void add(string &S,T x,int cPos=0,int cNode=0){
if(cPos==S.size()){
nodes[cNode].v = func(nodes[cNode].v,x);
return;
}
int c = encode(S[cPos]);
if(nodes[cNode].next[c]==-1){
nodes[cNode].next[c] = nodes.size();
nodes.push_back(node(wordSize,init_value,nodes[cNode].depth+1));
}
int nextNode = nodes[cNode].next[c];
add(S,x,cPos+1,nextNode);
}
void set_link(){
nodes[0].link = 0;
queue<int> Q;
Q.push(0);
while(Q.size()!=0){
int now = Q.front();
Q.pop();
nodes[now].v = func(nodes[now].v,nodes[nodes[now].link].v);
nodes[now].sum = func(nodes[now].sum,nodes[now].v);
for(int i=0;i<wordSize;i++){
int to = nodes[now].next[i];
if(to==-1)continue;
int x = now;
while(x!=0){
x = nodes[x].link;
if(nodes[x].next[i]!=-1){
x = nodes[x].next[i];
break;
}
}
nodes[to].link = x;
nodes[to].sum = func(nodes[to].sum,nodes[now].sum);
Q.push(to);
}
}
}
T query(string &S,int cPos = 0,int cNode=0){
T ret = init_value;
if(cPos==S.size())return ret;
int c = encode(S[cPos]);
int nextNode = nodes[cNode].next[c];
if(nextNode==-1){
if(nodes[cNode].link!=-1){
if(cNode!=0)ret = func(ret,query(S,cPos,nodes[cNode].link));
else ret = func(ret,query(S,cPos+1,cNode));
}
}
else{
ret = func(ret,nodes[nextNode].v);
ret = func(ret,query(S,cPos+1,nextNode));
}
return ret;
}
int encode(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<long long> T(26,0);
for(int i=0;i<M;i++){
string s;
cin>>s;
T.add(s,1);
}
T.set_link();
long long ans = T.query(S);
cout<<ans<<endl;
return 0;
}
沙耶花