hdu2222 输出可以匹配串数目 (附AC自动机模板)
裸ac自动机,end数组表示以其结尾的数目
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 struct AC 7 { 8 int next[500020][26],fail[500020],end[500010]; 9 int root,L; //根节点,总结点 10 int newnode() 11 { 12 for (int i=0;i<26;i++) 13 next[L][i]=-1; 14 end[L++]=0; 15 return L-1; 16 } 17 void init() 18 { 19 L=0; 20 root=newnode(); 21 } 22 void insert(char buf[]) 23 { 24 int len=strlen(buf),now=root; 25 for (int i=0;i<len;i++) 26 { 27 if (next[now][buf[i]-'a']==-1) 28 next[now][buf[i]-'a']=newnode(); 29 now=next[now][buf[i]-'a']; 30 } 31 end[now]++; 32 } 33 void build() 34 { 35 queue<int>q; 36 fail[root]=root; 37 for (int i=0;i<26;i++) 38 if (next[root][i]==-1) 39 next[root][i]=root; 40 else{ 41 fail[next[root][i]]=root; 42 q.push(next[root][i]); 43 } 44 while (!q.empty()) 45 { 46 int now=q.front(); 47 q.pop(); 48 for (int i=0;i<26;i++) 49 if (next[now][i]==-1) 50 next[now][i]=next[fail[now]][i]; 51 else{ 52 fail[next[now][i]]=next[fail[now]][i]; 53 q.push(next[now][i]); 54 } 55 } 56 } 57 int query(char buf[]) 58 { 59 int len=strlen(buf); 60 int now=root,res=0; 61 for (int i=0;i<len;i++) 62 { 63 now=next[now][buf[i]-'a']; 64 int temp=now; 65 while (temp!=root) 66 { 67 res+=end[temp]; 68 end[temp]=0; 69 temp=fail[temp]; 70 } 71 } 72 return res; 73 } 74 }; 75 char buf[1000010]; 76 AC ac; 77 int main() 78 { 79 int T,n,i; 80 scanf("%d",&T); 81 while (T--) 82 { 83 scanf("%d",&n); 84 ac.init(); 85 for (int i=0;i<n;i++) 86 { 87 scanf("%s",buf); 88 ac.insert(buf); 89 } 90 ac.build(); 91 scanf("%s",buf); 92 printf("%d\n",ac.query(buf)); 93 } 94 return 0; 95 }
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
模板及学习来自kuangbin巨博客
1 struct AC 2 { 3 int next[500020][26],fail[500020],end[500010]; 4 int root,L; //根节点,总结点 5 int newnode() 6 { 7 for (int i=0;i<26;i++) 8 next[L][i]=-1; 9 end[L++]=0; 10 return L-1; 11 } 12 void init() 13 { 14 L=0; 15 root=newnode(); 16 } 17 void insert(char buf[]) 18 { 19 int len=strlen(buf),now=root; 20 for (int i=0;i<len;i++) 21 { 22 if (next[now][buf[i]-'a']==-1) 23 next[now][buf[i]-'a']=newnode(); 24 now=next[now][buf[i]-'a']; 25 } 26 end[now]++; 27 } 28 void build() 29 { 30 queue<int>q; 31 fail[root]=root; 32 for (int i=0;i<26;i++) 33 if (next[root][i]==-1) 34 next[root][i]=root; 35 else{ 36 fail[next[root][i]]=root; 37 q.push(next[root][i]); 38 } 39 while (!q.empty()) 40 { 41 int now=q.front(); 42 q.pop(); 43 for (int i=0;i<26;i++) 44 if (next[now][i]==-1) 45 next[now][i]=next[fail[now]][i]; 46 else{ 47 fail[next[now][i]]=next[fail[now]][i]; 48 q.push(next[now][i]); 49 } 50 } 51 } 52 int query(char buf[]) 53 { 54 int len=strlen(buf); 55 int now=root,res=0; 56 for (int i=0;i<len;i++) 57 { 58 now=next[now][buf[i]-'a']; 59 int temp=now; 60 while (temp!=root) 61 { 62 res+=end[temp]; 63 end[temp]=0; 64 temp=fail[temp]; 65 } 66 } 67 return res; 68 } 69 }; 70 char buf[1000010]; 71 AC ac;