版本比较
题解:P5219 无聊的水题 I
正文
增加 68 行删除 1 行
13 行未改动141516171818192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919264 行未改动13 行未改动因为有 $n$ 个独立的数字,所以整个序列的 EGF 就是
$$G(x) = (F(x)) ^ n$$
我们最终需要的合法 Prufer 序列的数量,就是 $(n - 2)! \cdot [x ^ {n - 2}]G(x)$。到这里,用多项式快速幂就做完了。但如果你不会这些算法(比如我),可以继续往下看。我们最终需要的合法 Prufer 序列的数量,就是 $(n - 2)! \cdot [x ^ {n - 2}]G(x)$,用多项式快速幂就做完了,时间复杂度 $\mathcal{O}(n \log n)$。
:::success[代码]```cpp#include <bits/stdc++.h>using namespace std;using LL = long long;using V = vector<LL>;const int N = 2e5 + 5, M = 998244353;LL n, m, r[N], f[N];LL P(LL x, LL y) { LL s = 1; for (; y; x = x * x % M, y >>= 1) y & 1 && (s = s * x % M); return s;}void NTT(V &a, int p, int k) { for (int i = 0; i < k; i++) { i < r[i] && (swap(a[i], a[r[i]]), 1); } for (int d = 1; d < k; d <<= 1) { LL wn = P(~p ? 3 : (M + 1) / 3, (M - 1) / (d << 1)); for (int i = 0; i < k; i += (d << 1)) { LL w = 1; for (int j = 0; j < d; j++, w = w * wn % M) { LL x = a[i + j], y = a[i + j + d]; a[i + j] = (x + w * y % M) % M; a[i + j + d] = (x - w * y % M + M) % M; } } }}V X(V a, V b) { int n = a.size() - 1, m = b.size() - 1, k, l = 0; for (k = 1; k <= n + m; k *= 2, l++); for (int i = 0; i < k; i++) { r[i] = ((r[i >> 1] >> 1) | ((i & 1) << l - 1)); } a.resize(k), b.resize(k); NTT(a, 1, k), NTT(b, 1, k); V c(k); for (int i = 0; i < k; i++) c[i] = a[i] * b[i] % M; NTT(c, -1, k); for (LL &x : c) x = x * P(k, M - 2) % M; c.resize(::n - 1); return c;}V P(V x, LL y) { V s(1, 1); for (; y; x = X(x, x), y >>= 1) y & 1 && (s = X(s, x), 1); return s;}LL C(LL p) { LL k = p - 1, v = 1; V a; for (int i = 0; i <= k; i++) a.push_back(P(f[i], M - 2)); return f[n - 2] * P(a, n)[n - 2] % M;}int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> m; for (int i = f[0] = 1; i <= n; i++) f[i] = f[i - 1] * i % M; cout << (C(m) - C(m - 1) + M) % M; return 0;}```:::
---
这里还有一种不用多项式算法的做法:
考虑对 $G(x) = (F(x)) ^ n$ 两边同时求 $\ln$,有
$$\ln G(x) = n \cdot \ln F(x)$$
64 行未改动