单词(AC自动机)
程序员文章站
2022-06-04 12:22:28
...
思路
代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 1000010;
int n;
int tr[N][26], f[N],idx;//f存下的是每一个点走过的次数
int ne[N];
char str[N];
int id[210];
vector<int> v;//存下每一个入队的点
void insert(int x)
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int t = str[i] - 'a';
if (!tr[p][t]) tr[p][t] = ++ idx;
p = tr[p][t];
f[p] ++ ;
}
id[x] = p;
}
void build()
{
queue<int> q;
for (int i = 0; i < 26; i ++ )
if (tr[0][i])
q.push(tr[0][i]);
while (q.size())
{
int t = q.front();
q.pop();
v.push_back(t);
for (int i = 0; i < 26; i ++ )
{
int &p = tr[t][i];
if (!p) p = tr[ne[t]][i];
else
{
ne[p] = tr[ne[t]][i];
q.push(p);
}
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ )
{
scanf("%s", str);
insert(i);
}
build();
for (int i = idx - 1; i >= 0; i -- ) f[ne[v[i]]] += f[v[i]];
for (int i = 0; i < n; i ++ ) printf("%d\n", f[id[i]]);
return 0;
}
上一篇: 蒸米粉肉,热气腾腾的美食是隆冬里的必备品
下一篇: 芦笋头能吃吗,芦笋是怎么吃的