由于我懒得不想学蠢得学不会分治 \(\text{FFT}\) ,发现可以用多项式求逆来完整地代替...
文章节选自分治 FFT 与多项式求逆,转载方便自己查看。更多多项式求逆和分治 \(\text{FFT}\) 的内容与联系,可参见原博客。
问题提出
给定 \(\forall i\in[1,n),g[i]\),求递推式
\[f[i]=\begin{cases}1 & \text{ if } i=0 \\ \sum_{j=1}^if[i-j]g[j] & \text{ otherwise }\end{cases}\]
的前 \(n\) 项,即 \(\forall i\in[0,n),f[i]\) 。答案模费马质数。
求逆代替分治
这是分治 \(\text{FFT}\) 的板子,我们考虑用多项式求逆来解决这个问题。
考虑翻转 \(f\) 和 \(g\) 的地位
\[\begin{aligned}f[i]&=\sum_{j=1}^if[i-j]g[j]\\\Rightarrow g[i]&=f[i]-\sum_{j=1}^{i-1}f[j]g[i-j]\end{aligned}\]
令
\[h[i]=\begin{cases}1 & \text{ if } i=0\\ -g[i] & \text{ otherwise }\end{cases}\]
则
\[\begin{aligned}g[i]&=f[i]-\sum_{j=1}^{i-1}f[j]g[i-j]\\g[i]&=f[i]+\sum_{j=1}^{i-1}f[j](-g[i-j])\\g[i]&=f[i]h[0]+\sum_{j=1}^{i-1}f[j]h[i-j]\\g[i]&=\sum_{j=1}^if[j]h[i-j]\end{aligned}\]
我们需要让 \(j\) 的下界变成 \(0\),才能真正变成卷积。因此我们强行将 \(f[0]\) 置为 \(0\) 即可。为什么在这里不会出现问题?因为在这里,\(f[0]\) 根本不会和 \(h\) 做卷积(我们初始的下界就是 \(j=1\))。
\[\begin{aligned}g[i]&=\sum_{j=0}^if[j]h[i-j]\\G&=F\otimes H\end{aligned}\]
我们用多项式求逆算出 \(H^{-1}\),然后和 \(G\) 相乘即可得到 \(F\) 。
代码实现
#include <bits/stdc++.h>
using namespace std;
const int N = (100000+5)<<2, yzh = 998244353;
int n, g[N], h[N], f[N], tmp[N], R[N], len, L;
int quick_pow(int a, int b) {
int ans = 1;
while (b) {
if (b&1) ans = 1ll*ans*a%yzh;
b >>= 1, a = 1ll*a*a%yzh;
}
return ans;
}
void NTT(int *A, int o) {
for (int i = 0; i < len; i++) if (i < R[i]) swap(A[i], A[R[i]]);
for (int i = 1; i < len; i <<= 1) {
int gn = quick_pow(3, (yzh-1)/(i<<1));
if (o == -1) gn = quick_pow(gn, yzh-2);
for (int j = 0; j < len; j += (i<<1))
for (int k = 0, x, y, g = 1; k < i; k++, g = 1ll*g*gn%yzh) {
x = A[j+k], y = 1ll*g*A[i+j+k]%yzh;
A[j+k] = (x+y)%yzh, A[i+j+k] = (x-y)%yzh;
}
}
if (o == 1) return;
for (int i = 0, inv = quick_pow(len, yzh-2); i < len; i++)
A[i] = 1ll*A[i]*inv%yzh;
}
void poly_inv(int *A, int *B, int deg) {
if (deg == 1) {B[0] = quick_pow(A[0], yzh-2); return; }
poly_inv(A, B, (deg+1)>>1);
for (L = 0, len = 1; len <= (deg<<1); len <<= 1) ++L;
for (int i = 0; i < len; i++) R[i] = (R[i>>1]>>1)|((i&1)<<L-1);
for (int i = 0; i < deg; i++) tmp[i] = A[i];
for (int i = deg; i < len; i++) tmp[i] = 0;
for (int i = (deg+1)>>1; i < len; i++) B[i] = 0;
NTT(tmp, 1), NTT(B, 1);
for (int i = 0; i < len; i++) B[i] = 1ll*B[i]*(2ll-1ll*B[i]*tmp[i]%yzh)%yzh;
NTT(B, -1);
}
void work() {
scanf("%d", &n);
for (int i = 1; i < n; i++) scanf("%d", &g[i]);
h[0] = 1;
for (int i = 1; i < n; i++) h[i] = -g[i];
poly_inv(h, f, n);
for (int i = n; i < len; i++) f[i] = 0;
NTT(f, 1), NTT(g, 1);
for (int i = 0; i < len; i++) f[i] = 1ll*f[i]*g[i]%yzh;
NTT(f, -1); f[0] = 1;
for (int i = 0; i < n; i++) printf("%d ", (f[i]+yzh)%yzh);
}
int main() {work(); return 0; }