【AC自动机】单词频率

链接

单词频率

题目描述

某人读论文,一篇论文是由许多单词组成。但他发现一个单词会在论文中出现很多次,现在想知道每个单词分别在论文中出现多少次。

样例输入

3
a
aa
aaa

样例输出

6
3
1

思路

先用AC自动机
在串经过的节点都给它的sum值加上一
sum记录每个点到根所形成的串是多少个单词的前缀
然后用sum1表示答案,首先sum1显然等于sum
然后再想,nxt[u]一定在u前面,所以sum1[u] += sum1[nxt[u]]
最后把所有单词的结尾的sum1值输出就好了

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int n, tot, cnt;
int f[1000001], ch[10001][101], sum[1000001], q[100001], nxt[100001], r1[1000001];

char s[1000001];

void add()
{
	int len = strlen(s);
	int u = 1;
	for(int i = 0; i < len; ++i)
	{
		if(!ch[u][s[i] - 'a']) ch[u][s[i] - 'a'] = ++tot;
		u = ch[u][s[i] - 'a'];
		sum[u]++;
	}
	f[++cnt] = u;
	return ;
}

void bfs()
{
	int q1 = 1, q2 = 0;
	for(int i = 0; i <= 25; ++i)
		if(ch[1][i]) {
			q[++q2] = ch[1][i];
			nxt[ch[1][i]] = 1;
		}
	for(q1 = 1; q1 <= q2; ++q1)
	{
		int u = q[q1];
		for(int i = 0; i <= 25; ++i)
		{
			if(!ch[u][i]) ch[u][i] = ch[nxt[u]][i];
			else
			{
				q[++q2] = ch[u][i];
				nxt[ch[u][i]] = ch[nxt[u]][i];
			}
		}
	}
	for(int i = tot; i >= 1; --i)
		r1[q[i]] = sum[q[i]];
	for(int i = tot; i >= 1; --i)
		r1[nxt[q[i]]] += r1[q[i]];
}

int main()
{
	scanf("%d",&n);
	tot = 1;
	for(int i = 1; i <= n; ++i)
	{
		scanf("%s", s);
		add();		
	}
	bfs();
	for(int i = 1; i <= n; ++i)
		printf("%d\n",r1[f[i]]);
		
		
		return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值