---
id: 1685
lang: en
translation_of: index.md
source_sha256: 90d2f5797d472b242d6832a607782e343328423afebcea3e551f258e9262128c
title: "[Fortuna OJ] 6352 - Give (ca) Solution"
description: "When there are k leaves, a complete binary tree has 2k - 1 nodes; set up a DP to do the counting."
tags: ["OI","DP","Counting","Counting DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 给 rendered as “Give”; the file name (ca) is kept as written."
---

## 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.

<!--more-->

## Code

```cpp
// 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;
}
```
