#!/usr/bin/env python3 # O(N^2 W) solution using memoized recursion from functools import cache N, H, W = map(int, input().split()) books = list(tuple(map(int, input().split())) for _ in range(N)) orig = books[:] @cache def solve(w, i) -> bool: # is there a way to pack the first i books (i=1..n) so that the # stacked books take # up exactly width w (and otherwise stay within the H and W bounds) # and such that book 0 is at the bottom of the stack height, thickness = books[i - 1] # i'th book if i == 1: return height <= W and w == 0 # shelve the i'th book upright if height <= H and thickness <= w and solve(w - thickness, i - 1): return True # stack the i'th book if ( height <= books[0][0] and cumulative_thicknesses[i - 1] - w + thickness <= H and solve(w, i - 1) ): return True return False for base_id in range(N): solve.cache_clear() # reorder the instance so that base_id is at the bottom books = orig[:] if base_id != 0: books[0], books[base_id] = books[base_id], books[0] cumulative_thicknesses = [0] for book in books: cumulative_thicknesses.append(cumulative_thicknesses[-1] + book[1]) # look for solution for w in range(1, W - books[0][0] + 1): if solve(w, N): break else: continue # solution in hand, now recover it assert solve(w, N) upright = [] stacked = [0] for i in range(N, 1, -1): assert solve(w, i) height, thickness = books[i - 1] if thickness <= w and height <= H and solve(w - thickness, i - 1): upright.append(i - 1) w -= thickness elif ( height <= books[0][0] and cumulative_thicknesses[i - 1] - w + thickness <= H and solve(w, i - 1) ): stacked.append(i - 1) else: assert False # switch base_id "back" to its original name: if base_id in upright: upright[upright.index(base_id)] = 0 if base_id in stacked: stacked[stacked.index(base_id)] = 0 stacked[0] = base_id print("upright", *(i + 1 for i in upright)) sorted_stack = list(reversed(sorted(stacked, key=lambda i: orig[i][0]))) print("stacked", *(i + 1 for i in sorted_stack)) break else: print("impossible")