HDU 2222 Keywords Search

题目大意:询问匹配串中字典出现次数,不重叠。

题解:看我的指针AC自动机吓死你们。。。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<queue>
 6 #include<cstring>
 7 #define PAU putchar(' ')
 8 #define ENT putchar('
')
 9 using namespace std;
10 const int maxn=250000+10,sig=26;
11 struct ACauto{
12     struct node{node*ch[sig],*fail;int cnt;char x;}AC[maxn],*root;int nodecnt;
13     int id[156];queue<node*>RAM;
14     node*newnode(){
15         node*t;
16         if(!RAM.empty()) t=RAM.front();
17         else t=&AC[++nodecnt];
18         t->fail=root;t->cnt=0;
19         return t;
20     }
21     void init(){
22         for(int i=0;i<sig;i++) id[i+'a']=i;
23         root=&AC[0];root->cnt=0;root->x='#';nodecnt=0;return;
24     }
25     void insert(char*s){
26         int len=strlen(s);node*x=root;
27         for(int i=0;i<len;i++){
28             int c=id[s[i]];
29             if(!x->ch[c]) x->ch[c]=newnode();
30             x=x->ch[c];x->x=s[i];
31         } x->cnt++;return;
32     }
33     void getfail(){
34         queue<node*>Q;Q.push(root);
35         while(!Q.empty()){
36             node*x=Q.front();Q.pop();
37             for(int c=0;c<sig;c++){
38                 if(x->ch[c]){
39                     node*p=x->fail;while(p&&!p->ch[c])p=p->fail;
40                     x->ch[c]->fail=p?p->ch[c]:root;Q.push(x->ch[c]);
41                 } else x->ch[c]=x==root?root:x->fail->ch[c];
42             }
43         } return;
44     }
45     int query(char*s){
46         int len=strlen(s);node*x=root,*p;int sum=0;
47         for(int i=0;i<len;i++){
48             int c=id[s[i]];x=x->ch[c];
49             for(node*p=x;p&&p->cnt;p=p->fail){
50                 sum+=p->cnt;p->cnt=0;
51             }
52         } return sum;
53     }
54 }sol;
55 inline int read(){
56     int x=0,sig=1;char ch=getchar();
57     while(!isdigit(ch)){if(ch=='-')sig=-1;ch=getchar();}
58     while(isdigit(ch))x=10*x+ch-'0',ch=getchar();
59     return x*=sig;
60 }
61 inline void write(int x){
62     if(x==0){putchar('0');return;}if(x<0)putchar('-'),x=-x;
63     int len=0,buf[15];while(x)buf[len++]=x%10,x/=10;
64     for(int i=len-1;i>=0;i--)putchar(buf[i]+'0');return;
65 }
66 void init(){char s[51],t[1000001];
67     int n,T;
68     while(scanf("%d",&T)==1){
69         while(T--){
70             sol.init();
71             n=read();
72             while(n--){
73                 scanf("%s",s);
74                 sol.insert(s);
75             }
76             sol.getfail();
77             scanf("%s",t);
78             write(sol.query(t));ENT;
79         }
80     }
81     return;
82 }
83 void work(){
84     return;
85 }
86 void print(){
87     return;
88 }
89 int main(){init();work();print();return 0;}
原文地址:https://www.cnblogs.com/chxer/p/4556557.html