Problem E13. Numberlink Through an Oracle ≡

Author:Course Instructor   Time limit:10 sec
Input / output:interactive   Memory limit:512 Mb

Statement

A grid of h × w cells contains pairs of numbered endpoints. Connect every pair of equal numbers by a pipe so that a pipe runs through side-adjacent cells; pipes never cross or branch (an endpoint has exactly one connection, every other cell exactly two); every cell is used; and there are no closed loops: every pipe joins two endpoints with the same number.

As in "Sudoku Through an Oracle", the judge owns a SAT solver and your program may use it: encode the rules as a formula, ask the oracle, decode the answer. The catch: the local rules allow closed loops that touch no endpoint, and a compact formula cannot easily forbid all of them at once. When a model contains a loop, add a clause that forbids it and ask again; the oracle keeps all clauses between queries, so this loop of queries is cheap.

The protocol is that of "Sudoku Through an Oracle": a l1 ... 0 adds a clause; s a1 ... 0 solves under assumptions (flush, then read SAT with a model line in MODEL mode, UNSAT with the failed assumptions if there were any, or UNKNOWN); ans followed by the answer ends the dialogue. In DECISION mode the oracle answers only SAT or UNSAT.

Example: a puzzle with 3 rows and 4 columns, one solution, and its answer (cell (2,2) connects left and down: 4 + 2 = 6).

1 0 0 1      1 - 1 - 1 - 1       ans
2 0 0 3      2 - 2   3 - 3       8 12 12 4
2 0 0 3          |   |           8 6 10 4
             2 - 2   3 - 3       8 5 9 4

Input format

Line 1: the mode (MODEL or DECISION), the conflict budget of one query C and the maximum number of queries Q. Line 2: h and w. Then h lines of w integers: 0 for an empty cell, c > 0 for an endpoint of colour c; colours are 1,…,K and each appears exactly twice.

Output format

Oracle commands, then ans and h lines of w integers: the pipe mask of each cell, the sum of 1 (up), 2 (down), 4 (left) and 8 (right) over the sides through which the pipe leaves the cell. Connections must agree between neighbours. Any valid solution is accepted.

Constraints

6 ≤ h,w ≤ 30; every test has a solution. At most Q queries per test and at most 3 ⋅ 107 literals in all clauses together.

Groups: small (up to 10 × 10, MODEL), medium (12 × 12 to 15 × 15, MODEL), decision (up to 10 × 10, DECISION), large (17 × 17 to 20 × 20, MODEL), boss (25 × 25, 30 × 30, MODEL). As in other problems of the course, the boss group is out of reach of the authors' reference solution.


0.118s 0.008s 18