Problem solution · Python

ABC317 C — Remembering the Days

ABC317 C — Remembering the Days: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Dynamic programming
Source
KATO-Hiro AtCoder Solutions
Length
48 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 ABC317 C — Remembering the Days, 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

  • 48 lines of Python from the credited upstream file abc317_c.py.
  • The implementation visibly relies on ordered lookup, cached states.
  • No explicit 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 KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC317 C — Remembering the Days · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys     input = sys.stdin.readline     n, m = map(int, input().split())    pending = -1    dist = [[pending for _ in range(n)] for _ in range(n)]     for _ in range(m):        ai, bi, ci = map(int, input().split())        ai -= 1        bi -= 1         dist[ai][bi] = ci        dist[bi][ai] = ci     # print(dist)     # dp[s][v]: 訪問済みの頂点集合s、現在の頂点vとしたときの距離の最大値    inf = -(10**18)    dp = [[inf for _ in range(n)] for _ in range(1 << n)]     # 初期化: 頂点iを始点としたときの距離を0に    for i in range(n):        dp[1 << i][i] = 0     for s in range(1 << n):        for v in range(n):            if dp[s][v] == inf:                continue             for u in range(n):                # 未訪問 + 到達不可能な場合を除外                if not ((s >> u) & 1) and dist[v][u] != pending:                    dp[s | 1 << u][u] = max(dp[s | 1 << u][u], dp[s][v] + dist[v][u])     # 2次元のリストに対して、max(dp)とすると正しい答えが得られない    ans = max([max(dp_i) for dp_i in dp])    print(ans)  if __name__ == "__main__":    main() 

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 ↗