uva 1449

简单的AC自动机;

  1 #include<cstdio>
  2 #include<cstring>
  3 #include<queue>
  4 #define maxn 150005
  5 using namespace std;
  6 
  7 struct node
  8 {
  9     int cnt;
 10     int id;
 11     node *a[26],*tail;
 12 }no[maxn];
 13 int nonocount;
 14 node *newnode()
 15 {
 16     node *p=no+nonocount++;
 17     p->cnt=0;
 18     p->id=-1;
 19     memset(p->a,NULL,sizeof p->a);
 20     p->tail=NULL;
 21     return p;
 22 }
 23 
 24 void build(node *root,char *s,int x)
 25 {
 26     int l=strlen(s);
 27     for(int i=0;i<l;i++)
 28     {
 29         int k=s[i]-'a';
 30         if(root->a[k]==NULL)
 31             root->a[k]=newnode();
 32         root=root->a[k];
 33     }
 34     root->cnt++;
 35     root->id=x;
 36 }
 37 
 38 void gettail(node *root)
 39 {
 40     queue<node*>q;
 41     q.push(root);
 42     while(!q.empty())
 43     {
 44         node *fa=q.front();
 45         q.pop();
 46         for(int i=0;i<26;i++)
 47             if(fa->a[i]!=NULL)
 48             {
 49                 node *tmp=fa->tail;
 50                 while(tmp&&!tmp->a[i])tmp=tmp->tail;
 51                 if(!tmp)fa->a[i]->tail=root;
 52                 else fa->a[i]->tail=tmp->a[i];
 53                 q.push(fa->a[i]);
 54             }
 55     }
 56 }
 57 int num[200];
 58 void query(node *root,char *s)
 59 {
 60     int l=strlen(s);
 61     node *p=root,*tmp;
 62     for(int i=0;i<l;i++)
 63     {
 64         int k=s[i]-'a';
 65         while(!p->a[k]&&p!=root)p=p->tail;
 66         p=p->a[k];
 67         if(!p)p=root;
 68         tmp=p;
 69         while(tmp!=root)
 70         {
 71             if(tmp->cnt>=1)
 72             {
 73                 if(tmp->id!=-1)
 74                     num[tmp->id]++;
 75             }
 76             tmp=tmp->tail;
 77         }
 78     }
 79 }
 80 
 81 char s[1000006],t[159][100];
 82 int main()
 83 {
 84     int n;
 85     while(scanf("%d",&n)&&n)
 86     {
 87         memset(num,0,sizeof num);
 88         nonocount=0;
 89         node *p=newnode();
 90         for(int i=0;i<n;i++)
 91         {
 92             scanf("%s",t[i]);
 93             build(p,t[i],i);
 94         }
 95         gettail(p);
 96         scanf("%s",s);
 97         query(p,s);
 98         int ans=0;
 99         for(int i=0;i<n;i++)
100             ans=max(ans,num[i]);
101         printf("%d
",ans);
102         for(int i=0;i<n;i++)
103             if(ans==num[i])
104                 puts(t[i]);
105     }
106     return 0;
107 }
View Code
原文地址:https://www.cnblogs.com/yours1103/p/3396945.html