zoukankan      html  css  js  c++  java
  • AC自动机模板

    #include<bits/stdc++.h>
    using namespace std;
    
    const int maxn = 1e7 + 5;
    const int nsize = 26;
    
    struct node
    {
        node *next[nsize];
        node *fail;
        int sum;
    };
    
    int cnt;
    node *root;
    
    //构造字典树
    void Insert(char *s)
    {
        node *newnode,*p;
        p = root;
        for(int i = 0; s[i]; i++)
        {
            int x = s[i] - 'a';
            if(p->next[x] == NULL)
            {
                newnode=(struct node *)malloc(sizeof(struct node));
                for(int j=0; j<nsize; j++) newnode->next[j] = 0;
                newnode->sum = 0;
                newnode->fail = 0;
                p->next[x]=newnode;
            }
            p = p->next[x];
        }
        p->sum++;
    }
    
    //构造失败指针
    void build_fail() {
        queue<node*> Q;
        Q.push(root);
        while (!Q.empty()) {
            node *p = Q.front();
            Q.pop();
            for(int i = 0; i < nsize; i++) {
                if (p->next[i]) {
                    if (p == root)
                        p->next[i]->fail = p;
                    else {
                        node *tmp = p->fail;
                        while (tmp) {
                            if (tmp->next[i]) {
                                p->next[i]->fail = tmp->next[i];
                                break;
                            }
                            else tmp = tmp->fail;
                        }
                        if (!tmp) p->next[i]->fail = root;
                    }
                    Q.push(p->next[i]);
                }
            }
        }
        return ;
    }
    
    //匹配
    void ac_automation(char *ch)
    {
        node *p = root;
        int len = strlen(ch);
        for(int i = 0; i < len; i++)
        {
            int x = ch[i] - 'a';
            while(!p->next[x] && p != root)
            {
                p = p->fail;
                if(p->sum > 0)
                {
                    cnt += p->sum;  //不想改变sun值就用vis数组标记
                    p->sum = -1;
                }
            }
            p = p->next[x];
            if(!p) p = root;
            node *temp = p;
            while(temp != root)
            {
                if(temp->sum > 0)
                {
                    cnt += temp->sum;
                    temp->sum = -1;
                }
                else break;
                temp = temp->fail;
            }
        }
    }
  • 相关阅读:
    js事件监听机制(事件捕获)
    js预解析
    前端工程师也要关注代码版本控制
    BOM跟DOM的区别和关联
    web开发,click,touch,tap事件浅析
    prototype
    CSS:haslayout
    canvas画图
    第一个json解析:ps:(内容待完善)
    json解析实例
  • 原文地址:https://www.cnblogs.com/pach/p/7240097.html
Copyright © 2011-2022 走看看