题解:P11645 【MX-X8-T4】「TAOI-3」Warmth of the Eternity
题目大意
给定
求所有满足条件的树的数量对
题目解法
容易发现
这一步暂时先放着,待会儿用。
接下来设
-
当「删去
i 」时,j 所在连通块大小为c_{i, x}, 1 \le x \le d_i 。 -
当「删去
j 」时,i 所在连通块大小为c_{j, y}, 1 \le y \le d_j 。
在一棵树中,删除
那么我们可以得到一个重要结论:若
我们把节点的所有
问题:如何求出方案数?
我们先令
-
统计「纯粹的」方案数(不考虑重复):
- 当
k \neq n - k 时,两者必须一一匹对,所以这里的方案数为\text{cnt}_k! 。因为题目保证有解,所以\text{cnt}_k 必然等于\text{cnt}_{n - k} 。 - 当
n \equiv 0 \pmod{2} 时,我们需要配对\displaystyle\frac{\text{cnt}_{\frac{n}{2}}}{2} 对\displaystyle(\frac{n}{2}, \frac{n}{2}) ,设k = \displaystyle\frac{\text{cnt}_{\frac{n}{2}}}{2} ,那么此时的方案数为:
k!! = \frac{k!}{2^{\frac{k}{2}}(\frac{k}{2})!}. 这些式子相乘即可求出。
- 当
-
去除重复的方案:
- 我们发现这个算法会重复计算。举个例子,比如
\{2, 2, 3\} ,两个2 并无顺序可言,无论把「第1 个2 」匹配给邻居A ,把「第2 个2 」匹配给邻居B ,都对应一组同样的边\{(i, A), (i, B), (i, ?)\} ,只要这两个邻居在最终树中的度数信息等都吻合,就不能算作两种不同的树。 - 为了避免这个问题,我们对于每个节点
i ,将答案乘上\displaystyle\frac{1}{\text{mult}_{i, x}!} 即可。
- 我们发现这个算法会重复计算。举个例子,比如
综上,我们的答案可以表示为:
令
M 为:\left(\prod_{2k < n}\text{cnt}_k!\right) \times \begin{cases}(\frac{\text{cnt}_{\frac{n}{2}}}{2})!!, & n\text{ is even,}\\[6pt]1, & n\text{ is odd.}\end{cases} 令
D 为:\prod_{i = 1} ^ n \prod_{x}\left(\text{mult}_{i, x}!\right) 则答案为
\displaystyle\frac{M}{D} 。
复杂度分析
-
时间复杂度:
O(n + \log P) 。 -
空间复杂度
O(n) 。
代码实现
#include <bits/stdc++.h>
#define int long long
constexpr int N = 1e5 + 6, P = 998244353;
int power(int a, int b, int p) {
int ans = 1;
a %= p;
while (b > 0) {
if (b & 1) {
ans = ans * a % p;
}
a = a * a % p;
b >>= 1;
}
return ans;
}
void solve() {
int n;
std::cin >> n;
std::vector<int> d(n + 1, 0);
int sum = 0;
std::vector<int> freq(n + 1, 0);
std::vector<std::unordered_map<int, int>> cont(n + 1);
for (int i = 1; i <= n; ++i) {
std::cin >> d[i];
sum += d[i];
for (int j = 1; j <= d[i]; ++j) {
int sz;
std::cin >> sz;
++freq[sz];
++cont[i][sz];
}
}
int MAX = 2 * (n - 1);
std::vector<int> fact(MAX + 1, 0), ifact(MAX + 1, 0);
fact[0] = 1;
for (int i = 1; i <= MAX; ++i) {
fact[i] = fact[i - 1] * i % P;
}
ifact[MAX] = power(fact[MAX], P - 2, P);
for (int i = MAX - 1; i >= 0; --i) {
ifact[i] = ifact[i + 1] * (i + 1) % P;
}
int m = 1;
for (int k = 1; k * 2 < n; ++k) {
m = m * fact[freq[k]] % P;
}
auto so = [&](int x) -> int {
int res = fact[x];
res = res * power(power(2, x / 2, P), P - 2, P) % P;
res = res * ifact[x / 2] % P;
return res;
};
if (n % 2 == 0) {
int x = freq[n / 2];
m = m * so(x) % P;
}
int dd = 1;
for (int i = 1; i <= n; ++i) {
for (auto & kv : cont[i]) {
dd = dd * fact[kv.second] % P;
}
}
std::cout << m * power(dd, P - 2, P) % P;
}
int32_t main() {
std::ios::sync_with_stdio(0);
std::cin.tie(0), std::cout.tie(0);
int t;
// std::cin >> t;
t = 1;
while (t--) {
solve();
}
return 0;
}