1.ac自动机

  1A 妈妈呀

 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('\n')
 9 using namespace std;
10 const int maxn=1000000+10,inf=-1u>>1,sig=2;
11 struct node{
12     node*tx[sig],*fail;int cnt;node(){cnt=0;}
13 }ac[maxn],*nodecnt=ac,*root=nodecnt++;
14 void insert(char*s){
15     node*x=root;
16     for(int i=0;s[i];i++){
17         int c=s[i]-'a';
18         if(!x->tx[c])x->tx[c]=nodecnt++;
19         x=x->tx[c];
20     }x->cnt++;return;
21 }
22 void getfail(){
23     queue<node*>Q;for(int c=0;c<sig;c++)if(root->tx[c])Q.push(root->tx[c]);
24     while(!Q.empty()){
25         node*x=Q.front();Q.pop();
26         for(int c=0;c<sig;c++)if(x->tx[c]){
27             node*p=x->fail;while(p&&!p->tx[c])p=p->fail;if(!p)p=root;
28             x->tx[c]->fail=p->tx[c]?p->tx[c]:root;Q.push(x->tx[c]);
29         }
30     }return;
31 }
32 int query(char*s){
33     node*x=root;int sum=0;
34     for(int i=0;s[i];i++){
35         int c=s[i]-'a';
36         while(x&&!x->tx[c])x=x->fail;
37         x=x->tx[c];if(x->cnt)sum++;
38     }return sum;
39 }
40 inline int read(){
41     int x=0,sig=1;char ch=getchar();
42     while(!isdigit(ch)){if(ch=='-') sig=-1;ch=getchar();}
43     while(isdigit(ch)) x=10*x+ch-'0',ch=getchar();
44     return x*=sig;
45 }
46 inline void write(int x){
47     if(x==0){putchar('0');return;}if(x<0) putchar('-'),x=-x;
48     int len=0,buf[15];while(x) buf[len++]=x%10,x/=10;
49     for(int i=len-1;i>=0;i--) putchar(buf[i]+'0');return;
50 }
51 char s[maxn];
52 void init(){
53     scanf("%s",s);insert(s);getfail();
54     scanf("%s",s);write(query(s));
55     return;
56 }
57 void work(){
58     return;
59 }
60 void print(){
61     return;
62 }
63 int main(){
64     init();work();print();return 0;
65 }
ac

相关文章: