题目: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]]);
}