Acwing 1285 单词
题意:
给出n个单词,文章由n个单词组成,求每个单词在文章中的出现次数
思路:
实现:
#include <stdio.h>
#include <string.h>
const int N = 1e6 + 5;
int tr[N][26], idx = 1, nex[N], q[N], id[N], f[N];
char s[N];
void insert(int x)
{
int p = 0;
int len = strlen(s + 1);
for (int i = 1; i <= len; i++)
{
int t = s[i] - 'a';
if (!tr[p][t])
tr[p][t] = idx++;
p = tr[p][t];
f[p]++;
}
id[x] = p;
}
void build()
{
int hh = 1, tt = 0;
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[nex[t]][i];
else
{
nex[p] = tr[nex[t]][i];
q[++tt] = p;
}
}
}
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%s", s + 1);
insert(i);
}
build();
for (int i = idx - 1; i >= 1; i--)
f[nex[q[i]]] += f[q[i]];
for (int i = 1; i <= n; i++)
printf("%d\n", f[id[i]]);
return 0;
}