1285. 单词

题目链接

1285. 单词

某人读论文,一篇论文是由许多单词组成的。

但他发现一个单词会在论文中出现很多次,现在他想知道每个单词分别在论文中出现多少次。

输入格式

第一行一个整数 N,表示有多少个单词。

接下来 N 行每行一个单词,单词中只包含小写字母。

输出格式

输出 N 个整数,每个整数占一行,第 i 行的数字表示第 i 个单词在文章中出现了多少次。

数据范围

1N200,
所有单词长度的总和不超过 106

输入样例:

3 a aa aaa

输出样例:

6 3 1

解题思路

ac自动机

关键在于母串匹配匹配串时,如果匹配成功每次都要由 next 数组向上累加答案,这样会造成一个节点重复走,导致算法退化成 O(n2) 的复杂度,往回走的整个过程就是一棵树的形态,可以从列出树的拓扑序,从后往前走,即可一次性获得该节点的答案,另外树的拓扑序即 bfs 的逆过程,可利用构建ac自动机(本质上就是 bfs 的过程)获得

  • 时间复杂度:O(n)

代码

// Problem: 单词 // Contest: AcWing // URL: https://www.acwing.com/problem/content/1287/ // Memory Limit: 128 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } const int N=1e6+5; int trie[N][26],cnt[N],idx,pos[N],q[N],ne[N],n; char s[N]; void insert(int id) { int p=0; for(int i=0;s[i];i++) { int t=s[i]-'a'; if(!trie[p][t])trie[p][t]=++idx; p=trie[p][t]; cnt[p]++; } pos[id]=p; } void build() { int hh=0,tt=-1; for(int i=0;i<26;i++) if(trie[0][i])q[++tt]=trie[0][i]; while(hh<=tt) { int t=q[hh++]; for(int i=0;i<26;i++) { int p=trie[t][i]; if(!p)trie[t][i]=trie[ne[t]][i]; else { ne[p]=trie[ne[t]][i]; q[++tt]=p; } } } } int main() { cin>>n; for(int i=1;i<=n;i++) { cin>>s; insert(i); } build(); for(int i=idx-1;~i;i--)cnt[ne[q[i]]]+=cnt[q[i]]; for(int i=1;i<=n;i++)cout<<cnt[pos[i]]<<'\n'; return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/15994412.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示