HDU 2222 Keywords Search AC自动机模板
2015-06-16 21:13
471 查看
题目链接:
hdu2222
代码:
hdu2222
代码:
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<queue> using namespace std; struct node { int sum; node* fail; node* next[26]; node() { sum=0; fail=NULL; for(int i=0; i<26; i++) next[i]=NULL; } }; node* AC_insert(node* root,string word) { int len=word.size(); node* p=root; for(int i=0; i<len; i++) { if(!p->next[word[i]-'a']) p->next[word[i]-'a']=new node(); p=p->next[word[i]-'a']; } p->sum++; return root; } void build_fail(node* root) { queue<node*>q; node *p,*temp; q.push(root); while(!q.empty()) { p=q.front(); q.pop(); for(int i=0; i<26; i++) if(p->next[i]) { if(p==root) p->next[i]->fail=root; else { temp=p->fail; while(temp) { if(temp->next[i]) { p->next[i]->fail=temp->next[i]; break; } temp=temp->fail; } if(!temp) p->next[i]->fail=root; } q.push(p->next[i]); } } } int match(node* root,string s) { int len=s.size(),ans=0; node *p=root,*temp; for(int i=0;i<len;i++) { while(p!=root&&!p->next[s[i]-'a']) p=p->fail; p=p->next[s[i]-'a']; if(p==NULL) p=root; temp=p; while(temp!=root&&temp->sum!=-1) { ans+=temp->sum; temp->sum=-1; temp=temp->fail; } } return ans; } int main() { // freopen("in.txt","r",stdin); int T,n; node* root; string word,Target_str; scanf("%d",&T); while(T--) { root=new node(); scanf("%d",&n); for(int i=0; i<n; i++) { cin>>word; root=AC_insert(root,word); } build_fail(root); cin>>Target_str; printf("%d\n",match(root,Target_str)); } return 0; }
相关文章推荐
- swift down cast
- Kafka 之 中级
- CAS——实现单点登录
- javascrpt监听窗口关闭
- java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
- [BZOJ 1588] [HNOI 2002] 营业额统计
- UnigramProbability API
- awk内置变量的应用
- RHEL 6.3安装(超级详细图解教程)
- 一起talk C栗子吧(第十八回:C语言实例--输出十六进制)
- Memcache(MC)系列(六)Memcache内存分配策略
- hdu2993坡dp+二进制搜索
- 团队站立会议10(第二阶段)
- NGramBuffer API
- Fleury(弗罗莱)算法求欧拉路径
- java.lang.NoSuchMethodException: com.sun.proxy.$Proxy24.newSysUser()解决方案
- 快速排序和随机快速排序
- Memcache(MC)系列(五)使用memcache-top监控memcache集群状态
- java中的StringBuffer和StringBuilder
- LargeNGramModel API 语言模型