题解:P16780 ⌈Xzy OI R1 T2⌋ 成成边

· · 题解

题解 P16780 成成边

题目分析

给定 n 个字符串,建完全图,边权为两字符串的最长公共前缀(LCP)长度,求所有生成树的权值之和,答案对 10^9+7 取模。

核心难点:

  1. 直接枚举生成树会超时(生成树数量为 n^{n-2},指数级);
  2. 高效统计所有字符串两两之间的 LCP 总和;
  3. 结合凯莱定理完成最终计算。

解题思路

1. 贡献拆分(核心思想)

总答案 = 所有无序点对 (i,j) 的 LCP 长度 × 该点对在多少棵生成树中出现。

2. 凯莱定理应用

完全图 K_n 中,一条固定边会出现在 n^{n-3} 棵生成树中。 证明:

因此:

\text{答案} = \left( \sum_{1\le i<j\le n} \text{LCP}(s_i,s_j) \right) \times n^{n-3} \bmod 10^9+7

3. 高效计算 LCP 总和

暴力枚举所有点对计算 LCP 会超时,使用 Trie 树(字典树) 在线统计:

:::success[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;
}

:::

复杂度分析

完美适配题目数据范围(\sum |s_i| \le 2\times10^6)。