---
id: 1685
title: "「Fortuna OJ」6352 - 给(ca)题解"
slug: fortuna-oj6352-ca
lang: zh
date: 2019-09-15T23:02:28
date_gmt: 2019-09-15T15:02:28
modified: 2023-11-11T14:50:06
status: publish
password_protected: false
category: { name: Olympiad in Informatics, slug: oi }
tags: [OI, DP, 计数, 计数类DP]
original_url: https://kalorona.com/oi/fortuna-oj6352-给ca题解/
archived: 2026-11-27
editor: classic
media: []
archive_notes:
  - "Body headings were <h1> in the original; demoted to level 2 so the page title is the only h1."
  - "The display formula after 考虑以下转移 joined two lines with a bare \\\\ outside any environment, which MathJax 3 renders on one line; wrapped it in \\begin{gathered}…\\end{gathered} (the author did not align on =), TeX otherwise unchanged."
comments: []
---

## 主要思路

首先，叶子结点为$k$时，整个完整的二叉树存在$2k - 1$个节点。我们设置一个 DP 来进行计数。

考虑设置状态$dp[i][j]$为当前树已有$i$个节点，且有当前加入的节点到根的路径有$j$单位长度。考虑以下转移：

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

向新的节点加入统计数据：多了一个叶子结点，要么向左走，加深当前的路径；要么补上最后一个向左走的右节点。

然后就可以写代码了。

<!--more-->

## 代码

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