Problem solution · C++

ABC129 C — Typical Stairs

ABC129 C — Typical Stairs: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to michimani AtCoder Solutions.

Technique
Dynamic programming
Source
michimani AtCoder Solutions
Length
52 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For ABC129 C — Typical Stairs, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 52 lines of C++ from the credited upstream file abc129_c.cpp.
  • The implementation visibly relies on sequence storage, ordered lookup, cached states.
  • 2 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from michimani AtCoder Solutions by michimani and is used under the MIT licence.

Full codeABC129 C — Typical Stairs · C++C++
Use this to learn the idea, then write your own version.
#include <iostream>#include <map>#include <vector> using namespace std; int main() {    unsigned long long n, m;    cin >> n >> m;     vector<unsigned long long> dp(n + 1, 0);    map<unsigned long long, bool> halls;    unsigned long long prev_a = 0;    for (unsigned long long i = 0; i < m; i++) {        unsigned long long a;        cin >> a;         if (prev_a > 0 && a - prev_a == 1) {            cout << 0 << endl;            return 0;        }         prev_a = a;        halls[a] = true;    }     const unsigned long long div = 1000000007;    for (unsigned long long i = 1; i <= n; i++) {        if (halls.count(i) > 0) {            dp[i] = 0;            continue;        }         if (i == 1) {            dp[i] = 1;            continue;        } else if (i == 2) {            dp[i] = dp[1] == 0 ? 1 : 2;            continue;        }         unsigned long long p = dp[i - 1] + dp[i - 2];        p = p % div;         dp[i] = p;    }     cout << dp[n] << endl;     return 0;} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗