蓝魔法师

思路

树上问题求方案数,考虑树形,我们设置表示,当节点联通块数量是时,以为根节点的树上的方案数量。

显然我们可以做一个树上背包来枚举节点的连接情况,每次遍历一颗子树时枚举,要注意背包的枚举顺序均要从大到小开始枚举。

最后再特判一个不与这颗子树相连的特殊情况,也就是

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>

#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
    ll x = 0, f = 1; char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return x * f;
}

const int N = 2e3 + 10, mod = 998244353;

vector<int> G[N];

int dp[N][N], sz[N], n, m;

void dfs(int rt, int fa) {
    dp[rt][1] = sz[rt] = 1;
    for(int i : G[rt]) {
        if(i == fa) continue;
        dfs(i, rt);
        ll sum = 0;
        for(int j = 1; j <= sz[i] && j <= m; j++) sum = (sum + dp[i][j]) % mod;
        for(int j = min(m, sz[rt]); j >= 1; j--) {
            for(int k = min(m, sz[i]); k >= 1; k--) {
                if(j + k <= m) {
                    dp[rt][j + k] = (dp[rt][j + k] + 1ll * dp[rt][j] * dp[i][k]) % mod;
                }
            }
            dp[rt][j] = (dp[rt][j] * sum) % mod;
        }
        sz[rt] += sz[i];
    }
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    n = read(), m = read();
    for(int i = 1; i < n; i++) {
        int x = read(), y = read();
        G[x].pb(y);
        G[y].pb(x);
    }
    dfs(1, 0);
    int ans = 0;
    for(int i = 1; i <= m && i <= sz[1]; i++) ans = (ans + dp[1][i]) % mod;
    printf("%d\n", ans);
    return 0;
}