题意:给你n个单词,再给你一串字符,求在字符中有多少个单词出现过

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 10010
#define MAXLEN 1000010
struct node{
node *child[26];
node *fail;
int count;
void init(){
for(int i=0;i<26;i++)
child[i]=NULL;
count=0;
fail=NULL;
}
}*q[50*N];
node *root;
int head,tail;
void insert(char *str){//构建前缀树
node *now,*next;
int i=0,t;
now=root;
while(str[i]){
t=str[i]-'a';
if(now->child[t]!=NULL)
now=now->child[t];
else{
next=new node;
next->init();
now->child[t]=next;
now=next;
}
i++;
}
now->count++;
}
void build_fail(){
int i;
node *now,*p;
head=tail=0;
now=root;
q[tail++]=now;
while(head<tail){
now=q[head];
for(i=0;i<26;i++){
if(now->child[i]==NULL) continue;
if(now==root) now->child[i]->fail=root;
else{
p=now->fail;
while(p!=NULL){
if(p->child[i]!=NULL){
now->child[i]->fail=p->child[i];
break;
}
p=p->fail;
}
if(p==NULL) now->child[i]->fail=root;
}
q[tail++]=now->child[i];
}
head++;
}
}
int query(char *str){
node *now,*temp;
int i,t,cnt;
i=cnt=0;
now=root;
while(str[i]){
t=str[i]-'a';
while(now->child[t]==NULL&&now!=root) now=now->fail;
now=now->child[t];
if(now==NULL) now=root;
temp=now;
while(temp!=NULL&&temp->count!=-1){
cnt+=temp->count;
temp->count=-1;
temp=temp->fail;
}
i++;
}
return cnt;
}
int main(int argc, char** argv) {
int t,n;
char str[MAXLEN];
scanf("%d",&t);
while(t--){
scanf("%d",&n);
root=new node;
root->init();
while(n--){
scanf("%s",str);
insert(str);
}
build_fail();
scanf("%s",str);
printf("%d\n",query(str));
}
return 0;
}

最新文章

  1. 【bzoj1085】 SCOI2005—骑士精神
  2. ArrayList添加新元素的覆盖问题
  3. jQuery Layer mobile 弹出层
  4. [转] Finding the Best Programmer&#39;s Font
  5. echarts入门基础,画折线图
  6. 嵌入式Linux利用Wifi搭建无线服务器(物联网实践之无线网关)
  7. iOS 多线程下安全的使用定时器
  8. Oracle 调用存储过程执行CRUD的小DEMO
  9. 原生javascript-图片按钮切换
  10. oracle自动备份_expdp_Linux
  11. ZooKeeper 单机版安装和配置
  12. adb连接手机模拟器
  13. expdp、impdp 使用sys用户操作时的注意事项
  14. TF之BN:BN算法对多层中的每层神经网络加快学习QuadraticFunction_InputData+Histogram+BN的Error_curve
  15. (三)juc高级特性——虚假唤醒 / Condition / 按序交替 / ReadWriteLock / 线程八锁
  16. C#语言
  17. Disruptor并发框架简介
  18. iOS贝塞尔曲线(UIBezierPath)的基本使用方法
  19. 使用webbench做压力测试
  20. React-Router v4.0 hashRouter使用js跳转

热门文章

  1. SQL Server 2008空间数据应用系列五:数据表中使用空间数据类型
  2. shell printf格式化输出语句
  3. 生成excel文件
  4. C语言随笔_printf输出多行
  5. Liferay门户网站portal
  6. Zjnu Stadium(hdu3047带权并查集)
  7. linux进程间通信之管道篇
  8. IOS中设置状态栏的状态
  9. HDU 5794 - A Simple Nim
  10. DDD的&quot;waiting until GDB gets ready&quot;