题目:

小张最近在忙毕设,所以一直在读论文。一篇论文是由许多单词组成的。

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

输入

第一行一个整数N,表示有N个单词。接下来N行每行一个单词,每个单词都由小写字母('a'-'z')组成。(N≤200, 单词总长度不超过106)

输出

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

样例输入

3
a
aa
aaa

样例输出

6
3
1

提示

可以将论文内容看做'a aa aaa'。

题解:可以用AC自动机来解,插入单词的时候,在每个字母位置计数器加1,统计每个单词结尾的计数器即可。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm> using namespace std;
#define N 250
#define maxn 1000100
struct TNode
{
TNode *fail;
TNode *next[];
int cnt;
TNode()
{
cnt = ;
for(int i = ; i < ; i++)
next[i] = NULL;
fail = NULL;
return;
}
}; TNode *root;
int Tcnt;
TNode *TQ[N];
void Insert(const char *s)
{
int len = strlen(s);
TNode *p = root;
for(int i = ; i < len; i++)
{
if(p->next[s[i]-'a'] == NULL)
p->next[s[i]-'a'] = new TNode();
p = p->next[s[i]-'a'];
p->cnt++;
}
TQ[Tcnt++] = p;
return ;
} TNode *queue[maxn]; void build_ac_automation()
{
int front, rear;
front = rear = ;
root -> fail = root;
for(int i = ; i < ; i++)
{
if(root->next[i] != NULL)
{
root ->next[i]->fail = root;
queue[rear++] = root->next[i];
}
} while(front < rear)
{
TNode *p = queue[front++];
for(int i = ; i < ; i++)
{
TNode *q = p->fail;
if(p->next[i] == NULL) continue;
queue[rear++] = p->next[i];
while(q->next[i] == NULL && q!=root)
q = q->fail;
if(q->next[i] == NULL)
p->next[i]->fail = root;
else p->next[i]->fail = q->next[i];
}
}
while(rear>){
--rear;
queue[rear]->fail->cnt += queue[rear]->cnt;
}
return ;
} char s[]; int main()
{
int T,n;
while(~scanf("%d", &n))
{
Tcnt = ;
root = new TNode();
scanf("%d", &n);
for(int i = ; i < n; i++)
{
scanf("%s", s);
Insert(s);
}
build_ac_automation();
for(int i = ; i < n; i++)
printf("%d\n", TQ[i]->cnt); }
return ;
}

最新文章

  1. (转载)The One Sign You Will Be Rich-(by Brian de Haaff Founder and CEO Aha! -- world&#39;s #1 product roadmap software)
  2. SQL Server代理(3/12):代理警报和操作员
  3. PHP读取mssql,json数据中文乱码
  4. PHP获取MAC地址的函数代码
  5. C# 自定义序列化问题
  6. Oracle 删除数据后释放数据文件所占磁盘空间
  7. 用Apache Kafka构建流数据平台的建议
  8. extjs之TypeError: d.read is not a function解决方案
  9. 2014在百度之星程序设计大赛 - 资格 第四个问题 Labyrinth
  10. 大约session_cached_cursors在不同的db在默认不同的版本号
  11. ES6 - 变量的解构赋值学习笔记
  12. springMVC项目国际化(i18n)实现方法
  13. 在学习泛型时遇到的困惑经常与func&lt;T,U&gt;混淆
  14. poj 1015 Jury Compromise(背包变形dp)
  15. 进到页面后input输入框自动获取焦点
  16. CentOS上用Squid搭建HTTP代理小结
  17. LeetCode题解之Maximum Depth of N-ary Tree
  18. python read file(f,csv)
  19. Python: collections.nametuple()--映射名称到序列元素
  20. Linux文件共享(单进程之间、多进程之间)

热门文章

  1. win7x64 串口程序无法运行,提示:component &#39;MSCOMM32.OCX&#39; or one of its dependencies not correctlu registered。。。
  2. 通用 C# DLL 注入器injector(注入dll不限)
  3. 架构-层-DAL:DAL
  4. SQL数据库字段添加说明文字
  5. 【原创】基于phpGrace+uniApp开发之:5.登录界面增加图片验证码
  6. Java ——循环
  7. VS2008 项目启动时报:“无法直接启动带有类库输出类型的项目”
  8. sql 语句 的一些优化小总结
  9. data plugin for vs2019
  10. 20171110面试笔记 服务器端程序员+C/C++开发