Domino Tiling

Time limit5sMemory limit128 MB

Summary
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.
Level

Hard9 of 10

Topics
Graph, BFS, Greedy, Matrix
Solved
No attempts yet

Problem

There is a board with NN rows and MM columns, and every cell is numbered. The cell in the ii-th column from the left and the jj-th row from the top has number (j−1)×M+i(j-1)\times M + i. Thus the cell numbers run from 11 to N×MN\times M.

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 1×21\times 2 or 2×12\times 1 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 NN and MM separated by a space (1≤N,M≤1001 \le N, M \le 100). At least one of NN and MM is even. The second line contains the number of lines LL (0≤L≤5 0000 \le L \le 5\,000). Each of the following LL lines contains, separated by a space, the numbers of the two edge-adjacent cells that this line divides. All cell numbers are integers from 11 to N×MN\times M as defined above.

Output

If the board cannot be covered by dominoes under these rules, print −1-1 on the first line. Otherwise print the covering uniquely determined as follows.

For a covering, let pcp_c be the number of the cell paired with cell cc in the same domino. Choose the covering whose sequence (p1,p2,…,pNM)(p_1, p_2, \dots, p_{NM}) is lexicographically smallest. That is, give cell 11 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 22, cell 33, and so on.

For this covering, print the NM/2NM/2 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.

Examples4

  1. Example 1

    Input
    4 5
    9
    8 7
    13 14
    14 19
    6 7
    12 7
    4 9
    12 13
    14 9
    9 10
    
    Expected output
    1 6
    2 7
    3 4
    5 10
    8 9
    11 12
    13 18
    14 15
    16 17
    19 20
    
  2. Example 2

    Input
    1 2
    0
    
    Expected output
    1 2
    
  3. Example 3

    Input
    2 2
    0
    
    Expected output
    1 2
    3 4
    
  4. Example 4

    Input
    1 2
    1
    1 2
    
    Expected output
    -1