[AcWing面向模型编程]1285. 单词

题目:1285. 单词

分析:

若b串是a串的子串,那么b串一定也是a串某个前缀的后缀。因此我们从下往上遍历每个点,将其贡献加到其nex点即可(理论依据是:拓扑序)

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开long long见祖宗 
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endsl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> pii;
const ll mod = 1e9 + 7;
const int maxn = 1e6 + 10;
const int inf = 0x3f3f3f3f;

int tr[maxn][26], nex[maxn], num[maxn];
int id[maxn], q[maxn];
int tot;

void insert(char s[], int x)
{
	int now = 0;
	for(int i = 0; s[i]; i++)
	{
		if(!tr[now][s[i] - 'a']) tr[now][s[i] - 'a'] = ++tot;
		now = tr[now][s[i] - 'a'];
		num[now]++;
	}
	id[x] = now;
}

void build()
{
	int h = 1, t = 0;
	for(int i = 0; i < 26; i++)
		if(tr[0][i]) 
			q[++t] = tr[0][i];
	while(h <= t)
	{
		int fa = q[h++];
		for(int i = 0; i < 26; i++)
		{
			int &p = tr[fa][i];
			if(!p) p = tr[nex[fa]][i];
			else nex[p] = tr[nex[fa]][i], q[++t] = p;
		}
	}
}
int n;
char s[210];

int main()
{
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
		scanf("%s", s), insert(s, i);
	build();
	for(int i = tot; i >= 1; i--)
		num[nex[q[i]]] += num[q[i]];
	for(int i = 1; i <= n; i++)
		printf("%d\n", num[id[i]]);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值