One Last Trie

· · 题解

是的没错,32 兆,Trie 照样跑。

题意

约定 M 表示字符串长度的最值,M < 30。

按顺序给定 N 个长度不大于 M 的字符串 T_{1 \sim N}。

$$ p + \sum \limits_{i = 1}^{p} \operatorname{len}(\operatorname{LCP}(T_i, P)) $$ ## 题解 求 $\operatorname{LCP}$,很自然地想到建 Trie 去搞。 对于每个 $T_i$,在插入时,将其在 Trie 上对应的链的每一个节点的 cnt 加一,并在链尾节点处统计精确匹配的答案,存至 cnt。 对于每个 $P$,在 Trie 上一直尝试向下一个字符对应的节点跳,并将答案加上其节点的 cnt;如果成功匹配到串末,则答案直接置为此节点的 cnt。 但,传统的 Trie 会 MLE([我已经尽力了](https://www.luogu.com.cn/record/206374218),最大的点要 $\approx 86 MB$)。 所以要创新要发展。使用类似前向星的方式存 Trie,这只会让时间复杂度增加 $O(\lvert \Sigma \rvert)$,而此时空间复杂度变为 $O(NM)$。 实际上跑得飞快,目前是[最优解](https://www.luogu.com.cn/record/206375808),耗时小于第二的 $\frac{1}{2}$。 ## 代码 ```cpp #include <bits/stdc++.h> namespace SLV { #define rep(i, st, ed) for (int i = (st), _##i = (ed); i <= _##i; ++i) using namespace std; constexpr int N = 30002, M = 32; struct Node { char c; int cnt, head, nxt; } ch[N * M]; int n, q, tot; char s[M]; int insert(int u, char c) { // 在节点 u 处插入一个对应 c 的子节点 ch[++tot].nxt = ch[u].head; ch[tot].c = c; return ch[u].head = tot; } int find(int u, char c) { // 查询节点 u 是否有对应 c 的子节点 for (int i = ch[u].head; i; i = ch[i].nxt) if (ch[i].c == c) return i; return 0; } int main() { scanf("%d", &n); rep(i, 1, n) { scanf("%s", s + 1); int sl = strlen(s + 1), u = 0, v = ++ch[0].cnt, t; rep(j, 1, sl) { if (!(t = find(u, s[j]))) t = insert(u, s[j]); u = t; ++ch[u].cnt; v += ch[u].cnt; } ch[insert(u, '%')].cnt = v; // 插入结束符并统计答案 } scanf("%d", &q); rep(i, 1, q) { scanf("%s", s + 1); int sl = strlen(s + 1), j = 1, u = 0, ans = ch[0].cnt, t = find(u, s[j]); s[++sl] = '%'; for (; j <= sl && t; u = t, ++j, t = find(u, s[j]), ans += ch[u].cnt); printf("%d\n", ((j <= sl) ? ans : ch[u].cnt)); } return 0; } } // namespace SLV int main() { return SLV::main(); } ```