Domino Tiling
Time limit5sMemory limit128 MB
Find the lexicographically smallest way to tile an N by M grid with dominoes while respecting forbidden borders between certain adjacent cells, or report impossibility.
Problem
There is a board with rows and columns, and every cell is numbered. The cell in the -th column from the left and the -th row from the top has number . Thus the cell numbers run from to .
Lines are drawn on some of the borders between cells. Each line lies on the border between two edge-adjacent cells.
You want to cover the entire board with or dominoes so that there is no overlap and no empty cell. A single domino covers two edge-adjacent cells. However, if a line is drawn between two cells they cannot be covered by the same domino; if there is no line between them they may be covered together. Every cell must belong to exactly one domino.
Input
The first line contains two integers and separated by a space (). At least one of and is even. The second line contains the number of lines (). Each of the following lines contains, separated by a space, the numbers of the two edge-adjacent cells that this line divides. All cell numbers are integers from to as defined above.
Output
If the board cannot be covered by dominoes under these rules, print on the first line. Otherwise print the covering uniquely determined as follows.
For a covering, let be the number of the cell paired with cell in the same domino. Choose the covering whose sequence is lexicographically smallest. That is, give cell the smallest-numbered partner such that the rest of the board can still be fully covered under the rules, then do the same for cell , cell , and so on.
For this covering, print the dominoes. Print each domino on its own line as the numbers of the two cells it covers, with the smaller number first, separated by a space. Order the lines by increasing smaller number.