Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Induced Subgraphs with Fixed Degree

#include <atcoder/modint>
#include <bits/stdc++.h>

using namespace std;
using namespace atcoder;

using mint = modint998244353;

class Tree {
  public:
    int n;
    vector<vector<int>> adj;
    vector<vector<mint>> dp;
    // dp[i][d] is the count of induced connected subgraph such that the highest
    // vertex is node i and it has degree
    Tree(int n) {
        this->n = n;
        adj.resize(n);
        dp.resize(n, vector<mint>(n + 1, 0));
    }

    void dfs(int src, int par) {
        // Start with no children.
        dp[src][0] = 1;
        for (auto child : adj[src]) {
            if (child == par) {
                continue;
            }
            dfs(child, src);
            vector<mint> ndp(n + 1);
            for (int d = 0; d < adj[src].size(); d++) {
                // Ignore this children.
                ndp[d] += dp[src][d];
                for (int now = 0; now < adj[child].size(); now++) {
                    int nxt = d + 1;
                    // Append this children.
                    ndp[nxt] += dp[src][d] * dp[child][now];
                }
            }
            swap(dp[src], ndp);
        }
    }
};

void solve() {
    int n;
    cin >> n;

    Tree t(n);
    int m = n - 1;
    for (int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        t.adj[x].push_back(y);
        t.adj[y].push_back(x);
    }

    t.dfs(0, -1);
    mint ans = 0;
    auto &dp = t.dp;
    for (int i = 0; i < n; i++) {
        for (int d = 0; d < n; d++) {
            if (i == 0) {
                cout << dp[i][d].val() << " ";
            }
            ans += dp[i][d];
        }
    }
    cout << "\n";
    cout << ans.val() << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int i = 0; i < t; i++) {
        solve();
    }
    return 0;
}