hdu2222 ac自动机裸题
2016-07-18 16:54
260 查看
前几天讲了ac自动机,今天才a了第一道模板题.(o(╯□╰)o),我还是太弱了(毕竟蒟蒻).
问题难度很小,我注释的很详细了,应该能懂吧
问题难度很小,我注释的很详细了,应该能懂吧
#include <cstdio> #include <cmath> #include <iostream> #include <cstring> #include <algorithm> using namespace std; int t,tou,tail,n; char s[55],s1[100005]; struct node{ node *fail; node *net[26]; int ci; node() { fail=NULL; ci=0; for (int i=0;i<26;i++) { net[i]=NULL; } } }*q[500005]; node *root; void trie_build(char *s) //建立Trie { int temp, len; node *p = root; len = strlen(s); for(int i = 0; i < len; ++i) { temp = s[i] - 'a'; if(p->net[temp] == NULL) p->net[temp] = new node(); p = p->net[temp]; } p->ci++; } void ac_build() { q[tail++]=root;//初始化 while(tou!=tail) { node *p=q[tou++]; node *temp=NULL;//pop() for(int i = 0; i < 26; ++i) { if(p->net[i] != NULL) { if(p == root) //第一个元素fail必指向根 p->net[i]->fail = root; else { temp = p->fail; //失败指针 while(temp != NULL) //匹配为空 or 找到匹配 { if(temp->net[i] != NULL) { p->net[i]->fail = temp->net[i]; break; } temp = temp->fail; } if(temp == NULL) //为空则从头匹配 p->net[i]->fail = root; } q[tail++] = p->net[i]; //入队 } } } } int query() { node *p=root; int len=strlen(s1); int ans=0; for(int i=0;i<len;i++) { int temp=s1[i]-'a'; while (p->net[temp]==NULL&&p!=root)//跳转到fail指针 { p=p->fail; } p=p->net[temp]; if (p==NULL) p=root; node *w=p; while (w!=root&&w->ci!=-1) { ans+=w->ci; w->ci=-1; w=w->fail; } } return ans; } void readdata() { int t, num; scanf("%d", &t); while(t--) { tou= tail = 0; root = new node(); scanf("%d", &num); getchar(); for(int i = 0; i < num; ++i) { gets(s); trie_build(s); } ac_build(); scanf("%s", s1); printf("%d\n", query()); } } int main() { readdata(); }
相关文章推荐
- HDU4758 AC自动机+DP (HDU4758与HDU2222)
- AC自动机-一般算法实现
- 字符串的多模式匹配
- BZOJ1030 [JSOI2007]文本生成器【AC自动机+DP】
- BZOJ2434 [Noi2011]阿狸的打字机【AC自动机+dfs序+树状数组】
- AC自动机
- HDU_2222 大部分是别人的,有的地方稍有改动,代码有不完善的地方!
- AC自动机算法
- HDU-2222 Keyword Search
- AC自动机
- 【AC自动机】hdu2222 hdu2896 hdu3065 zoj3430 poj2778 hdu2243
- 【AC自动机】hdu2222 hdu2896 hdu3065 zoj3430 poj2778
- 两天AC自动机的学习 HDOJ2222 HDOJ 2896
- ac自动机+矩阵
- AC自动机——多模式串的匹配
- hdu 2222(AC自动机 裸题)
- hdu2222 ac自动机。。。。
- AC自动机复习总结
- BZOJ 2462: [BeiJing2011]矩阵模板
- poj3691DNA repair