void add() {
int len = strlen(s + 1);
int now = 0;
for(int i = 1;i <= len;++i) {
if(!trie[now][s[i] - 'a']) trie[now][s[i] - 'a'] = ++tot;
now = trie[now][s[i] - 'a'];
}
val[now]++;
}
void build() {
for(int i = 0;i < 26;++i) if(trie[0][i]) fail[trie[0][i]] = 0,q.push(trie[0][i]);
while(!q.empty()) {
int u = q.front();q.pop();
for(int i = 0;i < 26;++i) {
if(trie[u][i]) fail[trie[u][i]] = trie[fail[u]][i],q.push(trie[u][i]);
else trie[u][i] = trie[fail[u]][i];
}
}
}
int query() {
int now = 0;
int ans = 0;
int len = strlen(S + 1);
for(int i = 1;i <= len;++i) {
now = trie[now][S[i] - 'a'];
for(int j = now;j && val[j] != -1;j = fail[j]) ans += val[j],val[j] = -1;
}
return ans;
}
原文:https://www.cnblogs.com/wxyww/p/10128332.html