求目標(biāo)串中出現(xiàn)了幾個(gè)模式串
思路
一遭赂、構(gòu)建字典樹(shù)
二糯耍、構(gòu)建fail指針
三、串匹配
例題
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
namespace Trie{
int next[500010][26], fail[500010], end[500010];//字典樹(shù)变抽,fail指針匕坯,單詞末尾標(biāo)記
int root, L;//根節(jié)點(diǎn),樹(shù)節(jié)點(diǎn)計(jì)數(shù)
int new_node(){
for(int i = 0; i < 26; i++){
next[L][i] = -1;
}
end[L++] = 0;
return L-1;
}
void init(){
L=0;
root = new_node();
}
void insert(const char buf[]){//建立字典樹(shù)
int len = strlen(buf);
int now = root;
for(int i =0; i < len; i++){
if(next[now][buf[i]-'a'] == -1){//這里默認(rèn)都是小寫(xiě)字母
next[now][buf[i]-'a'] = new_node();
}
now = next[now][buf[i]-'a'];
}
end[now]++;
}
void build(){//構(gòu)建fail指針
queue<int> que;
fail[root] = root;
for(int i = 0; i < 26; i++){
if(next[root][i] == -1){
next[root][i] = root;//指向root說(shuō)明沒(méi)有
}else{
fail[next[root][i]] = root;
que.push(next[root][i]);
}
}
while(!que.empty()){
int now = que.front();
que.pop();
for(int i = 0; i < 26; i++){
if(next[now][i] == -1){
next[now][i] = next[fail[now]][i]; //沒(méi)有這個(gè)字符就去fail骄崩,方便遍歷不用判斷是否空
}else{
fail[next[now][i]] = next[fail[now]][i]; // 孩子的fail指針聘鳞,往自己fail方向找
que.push(next[now][i]);
}
}
}
}
int query(const char buf[]){
int len = strlen(buf);
int now = root;
int res = 0;
for(int i = 0; i < len; i++){
now = next[now][buf[i]-'a'];
int temp = now;
while(temp != root){
res += end[temp];
end[temp] = 0;
temp = fail[temp];
}
}
return res;
}
}
char buf[1000010];
int main(){
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
Trie::init();
for(int i=0;i<n;i++){
scanf("%s",buf);
Trie::insert(buf);
}
Trie::build();
scanf("%s",buf);
printf("%d\n",Trie::query(buf));
}
return 0;
}