Codeforces 250 E. The Child and Binary Tree [多项式开根 生成函数]

时间:2023-03-09 06:34:53
Codeforces 250 E. The Child and Binary Tree [多项式开根 生成函数]

CF Round250 E. The Child and Binary Tree

题意:n种权值集合C, 求点权值和为1...m的二叉树的个数, 形态不同的二叉树不同。

也就是说:不带标号,孩子有序

\(n,m \le 10^5\)


sro vfk picks orz

和卡特兰数很像啊,\(f_i\)权值为i的方案数,递推式

\[f[i] = \sum_{i\in C} \sum_{j=0}^{m-i}f[j]f[n-i-j]
\]

用OGF表示他

\[C(x)=\sum_{i\in C}x^i
\]

表示一个点的生成函数;

\[F(x) = \sum_{i=0}^m f_i x^i
\]

表示二叉树的生成函数。

根据生成函数乘法的定义,

\[F(x) = F^2(x) C(x) + 1
\]

其中1是因为空子树。

二次函数化简+分子有理化后得到

\[F(x) = \frac{2}{1 \pm \sqrt{1 - 4C(x) }}
\]

正负号怎么取?

\(F(0) = f_0 = 1\),所以只能取+号

然后多项式开根+多项式求逆就行啦!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = (1<<18) + 5;
inline int read(){
char c=getchar();int x=0,f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return x*f;
}
int P = 998244353, g = 3, inv2 = (P+1)/2;
inline int Pow(ll a, int b) {
ll ans = 1;
for(; b; b>>=1, a=a*a%P)
if(b&1) ans=ans*a%P;
return ans;
} namespace ntt {
int maxlen = 1<<18, rev[N];
ll omega[N], omegaInv[N];
void dft(int *a, int n, int flag) {
for(int i=0; i<n; i++) if(i < rev[i]) swap(a[i], a[rev[i]]); for(int l=2; l<=n; l<<=1) {
int m = l>>1;
ll wn = Pow(g, flag==1 ? (P-1)/l : P-1-(P-1)/l);
for(int *p = a; p != a+n; p += l) {
ll w = 1;
for(int k=0; k<m; k++) {
int t = w * p[k+m] %P;
p[k+m] = (p[k] - t + P) %P;
p[k] = (p[k] + t) %P;
w = w * wn %P;
}
}
}
if(flag == -1) {
ll inv = Pow(n, P-2);
for(int i=0; i<n; i++) a[i] = a[i] * inv %P;
}
} int t[N];
void inverse(int *a, int *b, int l) {
if(l == 1) {b[0] = Pow(a[0], P-2); return;}
inverse(a, b, l>>1);
int n = 1, k = 0; while(n < l<<1) n <<= 1, k++;
for(int i=0; i<n; i++) rev[i] = (rev[i>>1]>>1) | ((i&1)<<(k-1));
for(int i=0; i<l; i++) t[i] = a[i]; for(int i=l; i<n; i++) t[i] = 0;
dft(t, n, 1); dft(b, n, 1);
for(int i=0; i<n; i++) b[i] = (ll) b[i] * (2 - (ll) t[i] * b[i] %P + P) %P;
dft(b, n, -1);
for(int i=l; i<n; i++) b[i] = 0;
} int ib[N];
void square_root(int *a, int *b, int l) {
if(l == 1) {b[0] = 1; return;}
square_root(a, b, l>>1); int n = 1, k = 0; while(n < l<<1) n <<= 1, k++;
for(int i=0; i<n; i++) ib[i] = 0;
inverse(b, ib, l);
for(int i=0; i<n; i++) rev[i] = (rev[i>>1]>>1) | ((i&1)<<(k-1)); for(int i=0; i<l; i++) t[i] = a[i]; for(int i=l; i<n; i++) t[i] = 0;
dft(t, n, 1); dft(b, n, 1); dft(ib, n, 1);
for(int i=0; i<n; i++) b[i] = (ll) inv2 * (b[i] + (ll) t[i] * ib[i] %P) %P; dft(b, n, -1);
for(int i=l; i<n; i++) b[i] = 0;
}
} int n, m, c[N], a[N], f[N];
int main() {
freopen("in", "r", stdin);
n=read(); m=read()+1;
c[0] = 1;
for(int i=1; i<=n; i++) c[read()] -= 4;
for(int i=0; i<m; i++) if(c[i] < 0) c[i] += P; int len = 1; while(len < m) len <<= 1;
ntt::square_root(c, a, len);
a[0]++; if(a[0]>=P) a[0]-=P;
ntt::inverse(a, f, len);
for(int i=1; i<m; i++) printf("%d\n", f[i] * 2 %P);
}