Triangular Puzzle
Time limit1sMemory limit128 MB
Reconstruct a triangular 0/1 matrix from run-length block sequences given for every row and column, or report impossibility.
- Level
Hard8 of 10
- Topics
- Backtracking, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
Consider a triangular binary matrix filled with 0s and 1s. If its size is N, the 1st row and the 1st column each contain N cells, the 2nd row and the 2nd column each contain N-1 cells, and so on, until the Nth row and the Nth column each contain 1 cell. In other words, row i contains a_i,1, a_i,2, ..., a_i,N-i+1, and column j contains a_1,j, a_2,j, ..., a_N-j+1,j.
For a binary string, write down the lengths of all maximal consecutive blocks of 1s from left to right. This produces a sequence. For example, the string (0 1 1 0 1 1 1) produces the sequence (2 3). If there is no 1, the sequence is empty.
You are given this sequence for every row and every column. Write a program that reconstructs one triangular matrix satisfying all the given sequences.
If multiple matrices satisfy the conditions, print any one of them. If no such matrix exists, print No Answer.
Input
The first line contains the matrix size N. (1 <= N <= 20)
The next N lines give the sequence information for rows 1 through N. The following N lines give the sequence information for columns 1 through N.
Each information line has the following format.
h x1 x2 ... xh
h is the number of elements in the sequence for that row or column. x1, x2, ..., xh are the lengths of consecutive blocks of 1s in order. If h is 0, the line contains only h.
Output
If a triangular matrix satisfying the conditions exists, print it row by row. Print N values on the 1st row, N-1 values on the 2nd row, and so on, down to 1 value on the Nth row. Separate values in the same row with spaces.
a1,1 a1,2 ... a1,n-1 a1,n
a2,1 a2,2 ... a2,n-2 a2,n-1
...
an-1,1 an-1,2
an,1
If no matrix satisfies the conditions, print No Answer.