题解
考虑树上 dp,定义 表示在 的子树有 个连通块, 选不选的方案数。
初始化为 和 为 。
在 dfs 之后,枚举 表示当前 的子树有 个连通块。现在需合并 的信息,所以为书上背包。
再枚举 表示当前 的子树有 个连通块。
现在看 和 第三维不同的值会得出什么的结果呢。
| \ | ||
|---|---|---|
有以下转移式。
-
。
-
。
-
。
-
当且仅当 才有 。
其中 为未改动的 , 为未改动的 ,因为转移过程中 和 可能会被修改,答案可能变大。
最后,对于每个 ,答案为 ,其中 为你所定的根。
AC code:
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int p=998244353;
const int N=5e3+5;
int n;
int add(int x,int y){
ll res=1ll*x+y;
if(res>=p){
res-=p;
}
return res;
}
int mul(int x,int y){
ll res=1ll*x*y;
if(res>=p){
res%=p;
}
return res;
}
vector<int> g[N];
int sz[N];
int dp[N][N][2];//dp[i][j][0/1] 表示在 i 的子树有 j 个连通块,i 选不选。
void dfs(int u,int f){
dp[u][0][0]=dp[u][1][1]=sz[u]=1;
for(int v:g[u]){
if(v!=f){
dfs(v,u);
for(int i=sz[u];i>=0;i--){
int t0=dp[u][i][0],t1=dp[u][i][1];
dp[u][i][0]=dp[u][i][1]=0;
for(int j=sz[v];j>=0;j--){
dp[u][i+j][0]=add(dp[u][i+j][0],mul(t0,dp[v][j][0]));
dp[u][i+j][0]=add(dp[u][i+j][0],mul(t0,dp[v][j][1]));
dp[u][i+j][1]=add(dp[u][i+j][1],mul(t1,dp[v][j][0]));
if(i && j){
dp[u][i+j-1][1]=add(dp[u][i+j-1][1],mul(t1,dp[v][j][1]));
}
}
}
sz[u]+=sz[v];
}
}
}
signed main(){
//HAPPY!
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<n;i++){
int x,y;
cin>>x>>y;
g[x].push_back(y),g[y].push_back(x);
}
dfs(1,0);
for(int i=1;i<=n;i++){
cout<<add(dp[1][i][0],dp[1][i][1])<<"\n";
}
return 0;
}