Decorative Dominoes
Time limit1sMemory limit512 MB
Given an arrangement of n dominoes on a grid, assign each of the 2n ends an integer (0 to 10^6) so that touching ends share a number and no number appears more than twice, or report impossible.
- Level
Hard8 of 10
- Topics
- Graph, DFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
Marie likes dominoes. She is too young to fully understand the game, so she just makes arrangements based on this simple rule: each of the two ends of a domino must be adjacent to an end of another domino with the same number on it.

Figure D.1: Visualization of the first sample test case.
Today Marie found a large box of blank dominoes. This excites her because she can now show her full creativity: first she makes an unrestricted arrangement, then in a second step she paints numbers on both ends of all dominoes so that her simple rule is fulfilled.
She has already decided that putting the same number on each end of every domino is not satisfying enough. She wants to use each number at most twice. She does not restrict herself to numbers between and , and she also does not care if two dominoes have the same pair of numbers on them.
Marie places the dominoes along an integer grid so that each domino occupies exactly two neighbouring grid squares. Marie's arrangement does not have to be connected.
After Marie decides on an arrangement, she notices that choosing suitable numbers is harder than she first thought. Help her find a valid numbering for her arrangement or state that this is impossible.
Input
The input consists of:
- One line with an integer (), the number of dominoes in Marie's arrangement.
- lines, each with four integers , , , (), where and are the grid positions of the two ends of one domino.
All dominoes occupy two neighbouring positions in the integer grid and no two dominoes overlap.
Output
If a valid numbering exists, print lines, the th of which contains two numbers, the integers Marie should write on the two ends of the th domino. Output the numbers in the same order as the dominoes, including their two ends, appear in the input. All numbers in the output should be integers between and inclusive. If multiple valid numberings exist, you may output any one of them. If there does not exist a valid numbering, output impossible instead.