Child Play
Time limit1sMemory limit128 MB
Given domino-like slabs, orient and order them so both rows sum equally, discarding one slab only if necessary and preferring the smallest minimum half.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Greedy, Sorting, Implementation
- Solved
- No attempts yet
Problem
The people of the tiny island of Tookutoo love mathematics and teach their children several math games. One popular puzzle in Tookutoo is played with ceramic slabs like the ones shown below.

Each slab is like a domino: it is split into two halves, and each half has an integer printed on it. The three slabs above show the values [2, 1], [6, 3], and [3, 1]. A slab [a, b] may be flipped, so it can also be used as [b, a].
A player is given a set of slabs drawn at random from a large, varied pool. Using those slabs, the player must lay them side by side on the table so that the sum of the numbers in the top row equals the sum of the numbers in the bottom row. For the set shown above, one correct arrangement is:
1 6 1
2 3 3
Here the top row and the bottom row both add up to .
If no arrangement can use every slab, the player may discard exactly one slab — but the resulting equal sum must then be as large as possible. If several different slabs could be discarded while leaving that same largest sum, the player must discard the slab [a, b] (written with ) whose value is the smallest.
Write a program that, given a set of slabs, reports the equal sum of a valid arrangement, discarding one slab only when necessary.
Input
The input contains several test cases. The first line of each test case holds a single integer , the number of slabs (). Each of the next lines holds two integers and describing one slab (, ). A line containing marks the end of the input and is not a test case.
Output
For each test case, print a single line. If no valid arrangement exists even after discarding one slab, print impossible. Otherwise print the equal sum, followed by a description of the discarded slab: print discard X Y with when a slab had to be discarded, or discard none when every slab was used.