[DidaOJ][1134] Thanksgiving KK Special: Climbing Stairs

Problem Description

Loading...

Problem Analysis

Although the number of T test cases is 10000, the n values are actually only up to 30, which also suggests that it is best to use precomputation to construct the data.

It can be easily found that if $ dp[i] $ is used to represent the number of ways to climb to the $i$-th floor of stairs, then the following recurrence relation can be obtained:

$$ dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] $$

That is, the number of ways to climb to the $i$-th floor is equal to the number of ways to climb to the $i-1$ floor plus the number of ways to climb to the $i-2$ floor plus the number of ways to climb to the $i-3$ floor.

Note that the sample indicates that when n = 1, 0 should be output, but in the recurrence it is obvious that reaching the first floor also needs to be treated as one way, so $dp[1]$ needs to be initialized to $1$, and a special case is needed when outputting.

AC Code

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

int dp[32];

int main()
{
    dp[1] = 1;
    dp[2] = 1;
    dp[3] = 2;
    for (int i = 4; i < 32; ++i)
    {
        dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
    }

    int T;
    std::cin >> T;
    while (T--)
    {
        int n;
        std::cin >> n;
        if (n <= 1)
        {
            std::cout << 0 << std::endl;
        }
        else
        {
            std::cout << dp[n] << std::endl;
        }
    }
    return 0;
}

Problem address: Thanksgiving KK Special — Climbing Stairs - Problem Details - Problem - DidaOJ

Loading...