[LOG]AC自动机

#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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值