Approach
Sorting and greedy selection
For ABC445 D — Reconstruct Chocolate, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 51 lines of Python from the credited upstream file abc445_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def main():5 import sys6 7 input = sys.stdin.readline8 9 h, w, n = map(int, input().split())10 hw = []11 12 for i in range(n):13 hi, wi = map(int, input().split())14 hw.append((hi, wi, i))15 16 hw1 = sorted(hw)17 hw2 = sorted(hw, key=lambda x: (x[1], x[0]))18 used = set()19 pending = -120 ans = [(pending, pending)] * n21 y, x = 1, 122 23 while hw1 and hw2:24 if hw1[-1][0] == h:25 h1, w1, id1 = hw1.pop()26 ans[id1] = (y, x)27 28 x += w129 w -= w130 used.add(id1)31 elif hw2[-1][1] == w:32 h2, w2, id2 = hw2.pop()33 ans[id2] = (y, x)34 35 y += h236 h -= h237 used.add(id2)38 39 while hw1 and hw1[-1][-1] in used:40 hw1.pop()41 42 while hw2 and hw2[-1][-1] in used:43 hw2.pop()44 45 for ans_i in ans:46 print(*ans_i)47 48 49if __name__ == "__main__":50 main()51