hdu2896病毒侵袭(ac自动机,求模式串出现的个数)
2015-09-01 15:02
295 查看
题目连接:点击打开链接
题目描述:给定一些字符串和一些文本,找出每个文本中出现的所有字符串?
解题思路:很裸的一道ac自动机题目
代码:
题目描述:给定一些字符串和一些文本,找出每个文本中出现的所有字符串?
解题思路:很裸的一道ac自动机题目
代码:
#include <cstdio> #include <cstring> #include <queue> using namespace std; priority_queue<int,vector<int>,greater<int> >pq; struct Trie { int next[210*500][128],fail[210*500],ends[210*500]; int root,L,id; int newnode() { for(int i=0; i<128; i++) next[L][i]=-1; ends[L++]=0; return L-1; } void init() { L=0; id=0; root=newnode(); } void insert_Node(char buf[]) { int len=strlen(buf); int now=root; for(int i=0; i<len; i++) { if(next[now][buf[i]]==-1) next[now][buf[i]]=newnode(); now=next[now][buf[i]]; } ends[now]=++id; } void build() { queue<int> q; fail[root]=root; for(int i=0; i<128; i++) if(next[root][i]==-1) next[root][i]=root; else { fail[next[root][i]]=root; q.push(next[root][i]); } while(!q.empty()) { int now=q.front(); q.pop(); for(int i=0; i<128; i++) { if(next[now][i]==-1) next[now][i]=next[fail[now]][i]; else { fail[next[now][i]]=next[fail[now]][i]; q.push(next[now][i]); } } } } void query(char buf[]) { int len=strlen(buf); int now=root; for(int i=0; i<len; ++i) { now=next[now][buf[i]]; int temp=now; while(temp!=root) { if(ends[temp]!=0) pq.push(ends[temp]); temp=fail[temp]; } } } } tr; ///作为全局变量即可 char st[210]; char text[10010]; int n,m; int main() { while(scanf("%d",&n)==1) { tr.init(); for(int i=0; i<n; ++i) { scanf("%s",st); tr.insert_Node(st); } tr.build(); scanf("%d",&m); int sum=0; for(int i=1; i<=m; i++) { scanf("%s",text); tr.query(text); int len=pq.size(); int flag = -1;//标记重复出现的 int topp; if(len>0) { sum++; printf("web %d:",i); while(!pq.empty()) { topp = pq.top(); if(topp != flag) printf(" %d",pq.top()); flag = topp;; pq.pop(); } printf("\n"); } } printf("total: %d\n",sum); } return 0; }
相关文章推荐
- 在Ubuntu平台中读取CSV文件并用table进行展示
- Linux下使用MySQL"load data infile"出错的问题
- MFC之列表视图控件List Control
- python中时间格式
- js运算符
- Centos6部署nginx(一)
- CUDA tutorial 1
- 为什么你的APP不如人?因为你没有让它“活”起来
- android——RelativeLayout相对布局 相对对齐各属性值
- JavaScript动态修改图片的代码
- mysql 全局变量和SESSION变量
- JavaScript跨域访问CORS问题
- Improving neural networks by preventing co-adaptation of feature detectors (译文)
- foreach迭代语句
- MonkeyDevice API 教程
- NXP LPC-Link LPC3154
- 【POJ 1182 食物链】并查集
- JQuery+Json 省市区三级联动
- [Bluetooth(SDK)]使用WinSock搜索蓝牙设备
- 索引的分布式存储