当前位置:网站首页>AcWing 1285. 单词 题解(AC自动机)
AcWing 1285. 单词 题解(AC自动机)
2022-08-02 02:37:00 【QingQingDE23】
AcWing 1285. 单词
用f记录一个与这个后缀相同的单词前缀出现的次数(不仅仅是单词出现的次数)
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int tr[N][26], f[N], q[N];
int n;
string str;
int ids;
int id[N];
int ne[N];
void insert(int x){
int p = 0;
for(int i = 0; str[i]; i ++ ){
int t = str[i] - 'a';
if(!tr[p][t]) tr[p][t] = ++ ids;
p = tr[p][t];
f[p] ++ ; //记录前驱出现的次数
}
id[x] = p; //每个单词被赋予一个编号
}
void build(){
int hh = 0, tt = -1;
for(int i = 0; i < 26; i ++ ){
if(tr[0][i]) q[ ++ tt] = tr[0][i];
}
while(hh <= tt){
int t = q[hh ++ ];
for(int i = 0; i < 26; i ++ ){
int &p = tr[t][i];
if(!p) p = tr[ne[t]][i];
else{
ne[p] = tr[ne[t]][i];
q[ ++ tt] = p;
}
}
}
}
int main()
{
cin>>n;
for(int i = 0; i < n; i ++ ){
cin>>str;
insert(i);
}
build();
for(int i = ids - 1; i >= 0; i -- ){
f[ne[q[i]]] += f[q[i]]; //沿拓扑序倒序向上,将所有前驱节点的值累加到后继节点上
}
for(int i = 0; i < n; i ++ ){
cout<<f[id[i]]<<endl;
}
return 0;
}
边栏推荐
猜你喜欢
AI目标分割能力,无需绿幕即可实现快速视频抠图
IMU预积分的简单理解
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
[Server data recovery] Data recovery case of server Raid5 array mdisk disk offline
nacos startup error, the database has been configured, stand-alone startup
Flask之路由(app.route)详解
51. 数字排列
Analysis of the status quo of digital transformation of manufacturing enterprises
The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string
analog IC layout-Environmental noise
随机推荐
Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
字符串常用方法
JVM调优实战
字典常用方法
AI目标分割能力,无需绿幕即可实现快速视频抠图
列表常用方法
使用docker安装mysql
29. 删除链表中重复的节点
线程的不同状态
Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided
Use DBeaver for mysql data backup and recovery
canal同步Mariadb到Mysql
Nanoprobes纳米探针丨Nanogold偶联物的特点和应用
NIO's Sword
789. 数的范围
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案
analog IC layout-Parasitic effects
BI - SQL 丨 WHILE
53. 最小的k个数
EFCore 反向工程