Problem solution · Python

ABC412 D — Make 2-Regular Graph

ABC412 D — Make 2-Regular Graph: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Direct simulation
Source
KATO-Hiro AtCoder Solutions
Length
45 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

Direct simulation

For ABC412 D — Make 2-Regular Graph, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 45 lines of Python from the credited upstream file abc412_d.py.
  • The implementation visibly relies on ordered lookup.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

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 codeABC412 D — Make 2-Regular Graph · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys    from itertools import combinations     input = sys.stdin.readline     n, m = map(int, input().split())    graph = [[0 for _ in range(n)] for _ in range(n)]     for _ in range(m):        ai, bi = map(int, input().split())        ai -= 1        bi -= 1         graph[ai][bi] = 1        graph[bi][ai] = 1     edges = combinations(range(n), 2)    ans = 10**18     # M本の辺からN本の辺を選ぶ問題、と言い換え    for selected_edges in combinations(edges, n):        degrees = [0] * n         for ui, vi in selected_edges:            degrees[ui] += 1            degrees[vi] += 1         ok = all(degree == 2 for degree in degrees)         if not ok:            continue         # 追加する辺の本数N、削除する可能性がある辺の本数M、共通する辺の本数        ans = min(ans, n + m - 2 * sum(graph[ui][vi] for ui, vi in selected_edges))     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 ↗