AC自動機 多模匹配演算法

2022-05-21 18:48:11 字數 2429 閱讀 1188

寫了個模板題,加強版借鑑大佬的**,前置技能kmp(感覺沒啥用主要是思想),字典樹。

p3808 【模板】ac自動機(簡單版)

#include

#include

#include

#include

#include

#include

#include

#include

using

namespace std;

typedef

long

long ll;

const

int maxn =2*

1e6+9;

int trie[maxn][26

];//字典樹

int cntword[maxn]

;//記錄該單詞出現次數

int fail[maxn]

;//失敗時的回溯指標

int cnt =0;

void

insertwords

(string s)

cntword[root]++;

//當前節點單詞數+1

}void

getfail()

}//fail[now] ->當前節點now的失敗指標指向的地方

////tire[now][i] -> 下乙個字母為i+'a'的節點的下標為tire[now][i]

while

(!q.

empty()

)else

//否則就讓當前節點的這個子節點

//指向當前節點fail指標的這個子節點

trie[now]

[i]= trie[fail[now]

][i];}

}}intquery

(string s)

}return ans;

}int

main()

fail[0]

=0;getfail()

; cin >> s ;

cout <<

query

(s)<< endl;

return0;

}

p3796 【模板】ac自動機(加強版)

#include

#include

#include

#include

#include

#include

#include

using

namespace std;

struct tree//字典樹

ac[100000];

//trie樹

int cnt=0;

//trie的指標

struct result

ans[

100000];

//所有單詞的出現次數

bool

operator

<

(result a,result b)

string s[

100000];

inline

void

clean

(int x)

void

build

(string s,

int num)

now=ac[now]

.vis[s[i]

-'a'];

//向下構造

} ac[now]

.cnt=num;

//標記單詞結尾

}void

get_fail()

//構造fail指標

}while

(!q.

empty()

)//bfs求fail指標

else

//不存在這個子節點

ac[u]

.vis[i]

=ac[ac[u]

.fail]

.vis[i]

;//當前節點的這個子節點指向當

//前節點fail指標的這個子節點}}

}void

ac_query

(string s)

//ac自動機匹配

}int

main()

ac[0]

.fail=0;

//結束標誌

get_fail()

;//求出失配指標

cin>>s[0]

;//文字串

ac_query

(s[0])

;sort

(&ans[1]

,&ans[n+1]

);cout<.num

int i=

2; i<=n;

++i)

}return0;

}

ac自動機 匹配最長字首 多模匹配 AC自動機

精確的字串匹配演算法有 單模匹配演算法,比如,kmp bm演算法等 和 多模匹配演算法,比如,wu manber ac演算法等。ac演算法 aho corasick 是kmp演算法向多模式串情形的擴充套件,該演算法使用一種特殊的自動機,即ac自動機。ac自動機由一組模式串p生成,是trie的擴充套件...

AC自動機(字串多模匹配)

非常經典的乙個關於字串匹配的演算法 前置技能是 kmp和trie 重難點是fail指標 其實挺簡單的 其實不一定要會kmp,只要會它的思想就行了。所謂fail邊,其實就是乙個失敗指標,與kmp的next指標 類似於失敗指標,詳見我的kmp的部落格裡的p陣列 不同的是,next是對於乙個串而言的,而f...

AC自動機(多模式匹配)

ac自動機主要解決的問題 多模式匹配 kmp則屬於單模式匹配 n個單詞在m個字元的文章中,出現過多少次。主要分三步 構建trie樹 構建失敗指標 尋找匹配個數 trie樹 又稱字典樹 單詞查詢樹,是一種樹形結構,用於儲存大量的字串。它的優點是 利用字串的公共字首來節約儲存空間。具體參見 失敗指標 作...