luogu P3796 【模板】AC自动机(加强版)

知识点:1.一定要删掉调试信息

       2.数组别重名

code:

#include <bits/stdc++.h>
using namespace std;
int n;
int len[11102];
char c[10000002];
char a[10002][100];
int ans[100002];
struct ACtree
{
    int cnt;
    int f[220502],sfaf[220502];
     int ch[220502][27],val[220502];
     void init()
     {
         cnt = 0;
         memset(f,0,sizeof(f));
         memset(sfaf,0,sizeof(sfaf));
         memset(ch,0,sizeof(ch));
         memset(val,0,sizeof(val));
     }
     void insert(int t)
     {
         int u = 0;
         len[t] = strlen(a[t]);
         for(int i = 0;i < len[t];i++)
         {
             int k = a[t][i] - 'a';
             if(!ch[u][k])
             {
                 ch[u][k] = ++cnt;
                 u = ch[u][k];
             }
             else u = ch[u][k];
         }
         val[u] = t;
     }
     void getfail()
     {
         queue <int> q;
         q.push(0);
         while(!q.empty())
         {
             int u = q.front();
             q.pop();
             for(int i = 0;i < 26;i++)
             {
                 int v = ch[u][i];
                 if(!v){ch[u][i] = ch[f[u]][i];continue;}
                 q.push(v);
                 f[v] = u?ch[f[u]][i]:0;
                 sfaf[v] = val[f[v]]?f[v]:sfaf[f[v]];
             }
         }
     }
     void work()
     {
         int u = 0;
         int lena = strlen(c);
         for(int i = 0;i < lena;i++)
         {
             int k = c[i] - 'a';
             u = ch[u][k];
             if(val[u])
             {
                 ans[val[u]]++;
             }
             int v = u;
             while(sfaf[v])
             {
                 v = sfaf[v];
                 if(val[v])
                 {
                     ans[val[v]]++;
                 }
             }
         }
     }
}ac;
int main()
{//freopen("in.in","r",stdin);
    while(52016)
    {
        memset(ans,0,sizeof(ans));
        scanf("%d",&n);
        if(!n)return 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%s",a[i]);
            ac.insert(i);
        }
        ac.getfail();
        scanf("%s",c);
        ac.work();
        int maxn = 0;
        for(int i = 1;i <= n;i++)
        {
            maxn = max(maxn,ans[i]);
        }
        printf("%d
",maxn);
        for(int i = 1;i <= n;i++)
        {
            if(ans[i] == maxn){for(int j = 0;j < len[i];j++)printf("%c",a[i][j]);printf("
");}
        }
        ac.init();
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/xyj1/p/10529907.html