[LOG]AC自动机

#include
#include
#include
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;
        queuejoblist;
        joblist.push(pRoot);
        //pRoot->pFail is already NULL
        while (joblist.size()) {
            node *pCurrent = joblist.front();
            joblist.pop();
////////define/////////////
#define declare_i map::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
}

你可能感兴趣的:(数据结构,代码库,数据结构)