#include<iostream>
#include<queue>
#include<map>
using namespace std;
class AC_Trie {
const static char base_index = 'a';
struct node {
map<int, node*>pChild;
node *pFail;
bool terminate;
node() {
for (int i = 0;i < 26;i++)pChild[i] = 0;
pFail = 0;
terminate = 0;
}
}*pRoot;
node *Try(node *&target) {
if (target == NULL)target = new node;
return target;
}
bool built;
void Build_with_bfs() {
node *pScout, *pTemp;
queue<node*>joblist;
joblist.push(pRoot);
//pRoot->pFail is already NULL
while (joblist.size()) {
node *pCurrent = joblist.front();
joblist.pop();
define/
#define declare_i map<int, node*>::iterator i \
= pCurrent->pChild.begin()
end
for (declare_i;i != pCurrent->pChild.end();i++) {
define/
#define CurrentKey i->first
#define pNode i->second
end
pTemp = pNode->pFail;
if (pTemp == NULL)pCurrent->pFail = pRoot;
while (pTemp != NULL) {
pScout = pTemp->pChild[CurrentKey];
if (pScout != NULL) {
pCurrent->pChild[CurrentKey]->pFail
= pTemp->pChild[CurrentKey];
break;
}
pTemp = pTemp->pFail;
}
joblist.push(pNode);
}
}
built = 1;
}
public:
AC_Trie() {
pRoot = new node;
built = 0;
}
void Insert(string pat) {
node *scout = pRoot;
for (int i = 0;i < pat.size();i++)
Try(scout->pChild[pat[i] - base_index]);
scout->terminate = 1;
built = 0;
}
vector<int> Query(string text) {
if (built == false)Build_with_bfs();
//TODO: the biggest lie in the cs field
}
}inst;//instance
int main() {
inst.Insert("test1");
inst.Insert("test2");
vector<int>result = inst.Query("just a test1in test2fora case");
for (int i = 0;i < result.size();i++)
cout << result[i] << " ";
//should output: 7 15
}
[LOG]AC自动机
最新推荐文章于 2024-11-11 23:45:00 发布