Olympiad in Informatics

[Fortuna OJ] 6352 - Give (ca) Solution

Main Idea

First, when there are \(k\) leaves, the whole complete binary tree has \(2k - 1\) nodes. We set up a DP to do the counting.

Consider defining the state \(dp[i][j]\) as: the current tree already has \(i\) nodes, and the path from the currently added node to the root has length \(j\) units. Consider the following transitions:

\[ \begin{gathered} dp[i + 1][j + 1] += dp[i][j] \\ dp[i + 1][j - 1] += dp[i][j] \end{gathered} \]

Adding the new node to the count: there is one more leaf, and we either go left, deepening the current path, or fill in the right node for the last step that went left.

Then we can write the code.

Code

// FOJ6353.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 5050, mod = 998244353;

int dp[MAX_N << 1][MAX_N], n, m;

int main()
{
    freopen("ca.in", "r", stdin);
    freopen("ca.out", "w", stdout);
    scanf("%d%d", &m, &n);

    dp[1][0] = 1;

    for (int i = 1; i < (n << 1) - 1; i++)
    {
        for (int j = 0; j < min(m, i); j++)
        {
            dp[i + 1][j - 1] = (1LL * dp[i + 1][j - 1] + dp[i][j]) % mod;
            dp[i + 1][j + 1] = (1LL * dp[i + 1][j + 1] + dp[i][j]) % mod;
        }
    }
    for (int i = 1; i <= n; i++)
        printf("%d\n", dp[(i << 1) - 1][0]);
    return 0;
}