AcWing 1285. 单词
原题链接
中等
#include <bits/stdc++.h>
using namespace std;
const int N = 2e2+10,M = 5e6+10;
char str[M];
int id[M],cnt[M];
stack<int> sta;
struct Trie{
int nxt[M][26],fail[M],end[M];
int rt,tot;
int newnode()
{
for(int i = 0; i < 26; ++i)nxt[tot][i] = -1;
cnt[tot] = 0;end[tot] = 0;
return tot++;
}
void init()
{
tot = 0;
rt = newnode();
}
void insert(char *str,int i)
{
int p = rt;
for(int i = 0; str[i]; ++i)
{
if(nxt[p][str[i]-'a'] == -1) nxt[p][str[i]-'a'] = newnode();
p = nxt[p][str[i]-'a']; cnt[p]++;
}
end[p]++;
id[i] = p;
}
void build()
{
queue<int> q;
for(int i = 0; i < 26; ++i)
if(nxt[rt][i] == -1) nxt[rt][i] = rt;
else
{
fail[nxt[rt][i]] = rt;
q.push(nxt[rt][i]);
}
while(!q.empty())
{
int fa = q.front(); q.pop(); sta.push(fa);
for(int i = 0; i < 26; ++i)
if(nxt[fa][i] == -1) nxt[fa][i] = nxt[fail[fa]][i];
else
{
fail[nxt[fa][i]] = nxt[fail[fa]][i];
q.push(nxt[fa][i]);
}
}
}
void query()
{
while(!sta.empty())
{
cnt[fail[sta.top()]] += cnt[sta.top()];
sta.pop();
}
}
}ac;
int main()
{
int n; cin >> n;
ac.init();
for(int i= 1;i <= n; ++i)
{
scanf("%s",str);
ac.insert(str,i);
}
ac.build();
ac.query();
for(int i = 1; i <= n; ++i) printf("%d\n",cnt[id[i]]);
}