题解 P16780 成成边
题目分析
给定 个字符串,建完全图,边权为两字符串的最长公共前缀(LCP)长度,求所有生成树的权值之和,答案对 取模。
核心难点:
- 直接枚举生成树会超时(生成树数量为 ,指数级);
- 高效统计所有字符串两两之间的 LCP 总和;
- 结合凯莱定理完成最终计算。
解题思路
1. 贡献拆分(核心思想)
总答案 = 所有无序点对 的 LCP 长度 × 该点对在多少棵生成树中出现。
2. 凯莱定理应用
完全图 中,一条固定边会出现在 棵生成树中。 证明:
- 总生成树数:;
- 总边数:;
- 每条边的出现次数:。
因此:
3. 高效计算 LCP 总和
暴力枚举所有点对计算 LCP 会超时,使用 Trie 树(字典树) 在线统计:
- 插入字符串时,每走到一个节点,该节点的计数就是之前插入的字符串与当前字符串的公共前缀长度贡献;
- 累加所有节点的贡献,最终得到两倍的 LCP 总和(有序对),除以 2 就是无序对总和。
AC shit code
完整代码
#include<iostream>
#include<vector>
#include<string>
#include<array>
#define int long long
constexpr int mod = 1e9 + 7;
constexpr int maxk = 26; // 小写字母数量
// 快速幂:计算 a^b % mod,处理 b 为负数的情况
int qpow(int a, int b) {
if (b < 0) return 0;
int res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
// 字符映射:小写字母 -> 0~25
inline int toint(char p) {
return p - 'a';
}
// Trie 树节点结构体
struct node_t {
std::array<int, maxk> to; // 子节点下标
int cnt; // 经过该节点的字符串数量
node_t() : cnt(0) {
to.fill(0); // 初始化子节点为 0
}
};
// Trie 树封装
struct trie {
std::vector<node_t> node;
trie() {
clear();
}
// 新建节点,返回节点编号
int newnode() {
node.emplace_back();
return node.size() - 1;
}
// 清空 Trie 树,0 号为根节点
void clear() {
std::vector<node_t> tmp;
swap(tmp, node); // 高效清空
newnode();
}
// 插入字符串 s,返回当前串与之前所有串的 LCP 总和
int insert(const std::string& s) {
int now = 0, sum = 0;
for (char c : s) {
int k = toint(c);
// 无对应子节点则新建
if (!node[now].to[k])
node[now].to[k] = newnode();
now = node[now].to[k];
sum += node[now].cnt++; // 累加贡献并更新计数
}
return sum;
}
} tr;
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr); // 加速输入
int n;
std::cin >> n;
std::vector<std::string> str(n);
for (auto& s : str)
std::cin >> s;
int total = 0;
// 插入所有字符串,统计总 LCP 贡献(有序对)
for (auto& s : str) {
total = (total + tr.insert(s)) % mod;
}
// 特殊情况:n=1 无生成树,答案为 0
if (n == 1) {
std::cout << 0 << '\n';
return 0;
}
// 答案 = 总贡献 × n^(n-3) mod mod
int ans = total * qpow(n, n - 3) % mod;
std::cout << ans << '\n';
return 0;
}复杂度分析
- 时间复杂度:,所有字符串总长度;
- 空间复杂度:,Trie 树节点数等于字符串总字符数。
完美适配题目数据范围()。