hdu2222 Keywords Search (AC自动机板子
2024-08-23 22:24:31
https://vjudge.net/problem/HDU-2222
题意:给几个模式串和一个文本串,问文本串中包含几个模式串。
思路:贴个板子不解释。
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=26;
const int MAXN=500005;
struct Trie{
int next[MAXN][N],fail[MAXN],end[MAXN];
int root;
int tot;
int newnode()
{
for(int i=0;i<N;i++)
next[tot][i]=-1;
end[tot++]=0;
return tot-1;
}
void init()
{
tot=0;
root=newnode();
} void insert(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0;i<len;i++)
{
int k=buf[i]-'a';
if(next[now][k]==-1)
next[now][k]=newnode();
now=next[now][k];
}
end[now]++;
} void build()
{
queue<int> que;
fail[root]=root;
for(int i=0;i<N;i++)
if(next[root][i]==-1)
next[root][i]=root;
else
{
fail[next[root][i]]=root;
que.push(next[root][i]);
} while(!que.empty())
{
int now = que.front();
que.pop();
for(int i=0;i<N;i++)
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
que.push(next[now][i]);
}
}
} int query(char buf[])
{
int len=strlen(buf);
int now=root;
int res=0;
for(int i=0;i<len;i++)
{
now=next[now][buf[i]-'a'];
int temp=now;
while(temp!=root)
{
res+=end[temp];
end[temp]=0;//模式串只在主串中匹配一次就可以了
temp=fail[temp];
}
}
return res;
} };
Trie ac;
char buf[MAXN+MAXN];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
ac.init();
for(int i=0;i<n;i++)
{
scanf("%s",buf);
ac.insert(buf);
}
ac.build();
scanf("%s",buf);
printf("%d\n",ac.query(buf));
} return 0;
}
最新文章
- Delphi_03_Delphi_Object_Pascal_基本语法_01
- SQL Server 行转列重温
- markdown安装和使用
- [Asp.Net]获取客户端ip和mac地址
- 自己通过Cygwin编译的windows下的redis3.2.6
- eclipse svn 忽略 target目录 等等... 我用的后边的方法 (转载)
- WSDL相关文档
- Axis学习的第一天
- The Swift Programming Language-官方教程精译Swift(4)字符串和字符
- Failed to connect to Xilinx hw_server. Check if the hw_server is running and correct TCP port is used.
- ngRx 官方示例分析 - 1. 介绍
- C++回顾day03---<;输入输出流>;
- php中print、echo、print_r、var_dump的区别
- Win7 VS2017编译Godot3.0.2和2.1.4
- flask 定义数据库关系(一对一)
- AJPFX平台:中国的经济是个大泡沫吗?这个泡沫即将崩解吗?
- Spring 概念
- 设计模式-装饰者模式(Decorator Pattern)
- HDU 1518 Square(DFS)
- PLSQL Developer 客户端没有TNS监听,无法连接数据库