Title effect: There $ $ n-strings, each string seek times all occur in a string
Problem solution: $ AC $ automata, each node is after $ sz $ plus one, a string of occurrences for each $ fail $ trees and $ sz $ subtree
Point card: $ AC $ automaton root node is $ 1 $, $ build $ in no time all the empty $ nxt [1] [i]assigned the $ 1 $
C++ Code:
#include <cstdio> #include <algorithm> #include <iostream> #include <queue> const int maxn = 1e6 + 10; std::string s; int n, ret[210]; namespace AC { int nxt[maxn][26], fail[maxn], idx = 1, cnt[maxn]; int insert(std::string s) { int p = 1; for (char ch : s) { if (nxt[p][ch - 'a']) p = nxt[p][ch - 'a']; else p = nxt[p][ch - 'a'] = ++idx; ++cnt[p]; } return p; } void build() { static std::queue<int> q; for (int i = 0; i < 26; ++i) if (nxt[1][i]) fail[nxt[1][i]] = 1, q.push(nxt[1][i]); else nxt[1][i] = 1; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < 26; ++i) if (nxt[u][i]) fail[nxt[u][i]] = nxt[fail[u]][i], q.push(nxt[u][i]); else nxt[u][i] = nxt[fail[u]][i]; } } int head[maxn], CNT; struct Edge { int to, nxt; } e[maxn]; void addedge(int a, int b) { e[++CNT] = (Edge) { b, head[a] }; head[a] = CNT; } void dfs(int u) { for (int i = head[u], v; i; i = e[i].nxt) { v = e[i].to; dfs(v); cnt[u] += cnt[v]; } } void solve() { for (int i = 2; i <= idx; ++i) addedge(fail[i], i); dfs(1); } } int main() { std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0); std::cin >> n; for (int i = 0; i < n; ++i) { std::cin >> s; ret[i] = AC::insert(s); } AC::build(), AC::solve(); for (int i = 0; i < n; ++i) std::cout << AC::cnt[ret[i]] << '\n'; return 0; }