Frontier states
Suppose every cell strictly to the left of the current column has been filled. Since a horizontal straight tromino has length , tiles already placed can occupy cells only in the current and next columns. Encode these four cells as a bitmask: bits represent the top and bottom cells of the current column, and bits represent those of the next column.
Place a tile covering the first empty cell of the current column. Once that column is full, shift the mask right by two bits. Always choosing the first empty cell avoids counting the same tiling in different placement orders. Start at mask and accept only mask after processing columns.
The reachable masks are . Vertical reflection gives equal counts for symmetric masks. After columns, define six quantities:
Each quantity stores the count of one mask, not the sum of a symmetric pair. Enumerating placements covering the first empty cell gives the following transitions.
Linear DP and matrix exponentiation
Evaluating the transitions times takes time and space, sufficient for subtask 2. For the full constraints, write the six quantities as a column vector with , where
Binary exponentiation computes in time and space. Perform all arithmetic modulo .
Recurrence used in the supplied code
The transition matrix satisfies
Hence, for ,
with
The supplied linear solution evaluates this recurrence directly. The main solution exponentiates its companion matrix on the state . Represent the coefficient by the modulus minus one, and store the exponent in a 64-bit integer.
Small-case search
For subtask 1, represent all board cells by a bitmask and try every tile covering the first empty cell. Memoize each occupied-cell mask. Filling cells from left to right leaves only a constant number of frontier states per column, since protrusions span at most two future columns. Scanning for the first empty cell gives time and stored states. The independent naive implementation uses at most 40 bits for the whole board.
Both straight and L-shaped trominoes are required. A vertical straight tromino does not fit in a height-two board. The empty-board value is an internal base case; input never has .
Reduce after each multiply-add. Each intermediate is at most , so signed 64-bit arithmetic suffices.
Solution written by GPT