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

    #include<cstdio>
    #include<queue>
    using namespace std;
    struct node {node *nxt[26],*fail;int val;};
    node mem[500010]; int cnt;
    inline node *alloc() {return mem+cnt++;}
    void ins(node *root,char *s) {
        while(*s!=0) {
            int v=*s++-'a';
            if(!root->nxt[v])root->nxt[v]=alloc();
            root=root->nxt[v];
        }
        root->val++;
    }
    queue<node*>q;
    void build(node *root) {
        for(int i=0; i<26; i++) if(root->nxt[i])root->nxt[i]->fail=root,q.push(root->nxt[i]);
        while(!q.empty()) {
            node *u=q.front();q.pop();
            for(int i=0; i<26; i++)
                if(u->nxt[i])u->nxt[i]->fail=u->fail->nxt[i],q.push(u->nxt[i]);
                else u->nxt[i]=u->fail->nxt[i];
        }
    }
    int query(node *root,char *s) {
        int ans=0;
        while(*s!=0) {
            root=root->nxt[*s++-'a'];
            for(node *t=root; t&&~t->val; t=t->fail)ans+=t->val,t->val=-1;
        }
        return ans;
    }
    int n;
    char p[1000005];
    int main() {
        node *root=alloc();
        scanf("%d",&n);
        for(int i=1; i<=n; i++)scanf("%s",p),ins(root,p);
        build(root);
        scanf("%s",p); printf("%d
    ",query(root,p));
        return 0;
    }
    

    Luogu P3838板子题。

    (啊啊啊为什么我自带大常数用指针还这么慢啊啊啊啊)$epsilon varepsilon$

  • 相关阅读:
    网络编程
    并发编程-线程池
    并发编程-集合
    并发编程-AQS
    并发编程-CAS
    并发编程-volatile和synchronized的区别
    并发编程-synchronized
    并发编程-java内存模型
    JVM-分代垃圾回收器
    性能优化
  • 原文地址:https://www.cnblogs.com/TheRoadToAu/p/8849866.html
Copyright © 2011-2022 走看看