Keywords Search(查找关键字)
2011-08-30 21:55
267 查看
hdoj 2222
题目大意:给出一些字符串 ,再给出一段文字,问文字中出现多少个单词
解决:AC自动机
#include <iostream> #include <cstring> #include <queue> #include <cstdio> using namespace std; #define s scanf int top; struct node { int cnt; int fail; int next[26]; }; node tree[400000]; char mai[1000005]; void init() { top=1; memset(tree[0].next,0,sizeof(tree[0].next)); //刚开始的时候初始化,是在node的构造函数中实现的,但是由于是多组测试数据,所以 //错误了好几次这次,就应该在初始化,和需要新的结点的时候在初始化 tree[top].cnt=0; } void insert_trie(char str[]) { int id,i=0; while(*str) { id=*str-'a'; if(!tree[i].next[id]) { tree[i].next[id]=top; memset(tree[top].next,0,sizeof(tree[top].next)); tree[top].cnt=0; top++; } i=tree[i].next[id]; str++; } tree[i].cnt++; } void build_fail() { tree[0].fail=-1; queue<int> q; q.push(0); while(!q.empty()) { int now=q.front(); q.pop(); for(int i=0;i<26;i++) { int tmp=tree[now].next[i]; if(tmp) { int p; for(p=tree[now].fail;p!=-1;p=tree[p].fail) if(tree[p].next[i]) { tree[tmp].fail=tree[p].next[i]; break; } if(p==-1){tree[tmp].fail=0;} q.push(tmp); } } } } void query(char str[]) { int id,sum=0,p=0; while(*str) { id=*str-'a'; //不匹配的情况,找到根节点,或者是找到匹配的地方 while(tree[p].next[id]==0 && p)p=tree[p].fail; if(tree[p].next[id]==0)p=0; else p=tree[p].next[id]; //匹配或者是根节点的情况,沿着fail一直找到跟,将所有的一该字母结束的串的情况 都 算上。 int tmp=p; while(tmp && tree[tmp].cnt) { sum+=tree[tmp].cnt; tree[tmp].cnt=0; tmp=tree[tmp].fail; } str++; } printf("%d\n",sum); } int main() { int icase; s("%d",&icase); while(icase--) { init(); int n; char str[60]; s("%d",&n); while(n--) { s("%s",str); insert_trie(str); } build_fail(); s("%s",mai); query(mai); } // system("pause"); return 0; }
相关文章推荐
- eclipse查找文件(即eclipse file search ) 两个关键字,Ctrl+H,怎么做到?
- 使用BlockingQueue在给定的某个文件夹下查找给定的关键字keywords
- 查找关键字算法:静态查找表(Static Search Table)
- myeclipse search查找打开第二个文件时第一个文件被关闭关闭
- hdoj 2222 Keywords Search 【AC自动机 入门题】 【求目标串中出现了几个模式串】
- 根据关键字查找所需要的字段或者某一行
- 二叉查找树——Validate Binary Search Tree
- LeetCode OJ 之 Search in Rotated Sorted Array (有序数组翻转后的查找)
- hdu 2222Keywords Search(AC自动机入门好题)
- leetcode 刷题之路 35 Search in Rotated Sorted Array II (旋转排序数组查找终极版)
- Ubuntu查找文件夹中内容包含关键字的文件(OpenCV中查找对应函数定义的技巧)
- php数组查找函数in_array()、array_search()、array_key_exists()使用实例
- Shell中遍历整个目录查找某个关键字
- HDU 2222 Keywords Search——AC自动机
- hdu 2222 Keywords Search(ac自动机水题)
- LeetCode OJ 之 Search in Rotated Sorted Array II (有序数组翻转后的查找 - 二)
- java利用关键字实现查找文件
- 在指定目录下的文件中查找关键字
- java 遍历指定目录下的文件夹并查找包含指定关键字的文件
- HDU - 2222 Keywords Search(AC自动机=KMP+字典树)