Consider a board consisting of a rectangle with 4 squares x 10 squares. A square of 1 square x 1 square is called a block.
Tetromino is a combination of four blocks, and there are the following seven types (and those that have been rotated 90 degrees arbitrarily).
Now, consider the situation where blocks are placed on 28 squares on the board.
As shown in the figure on the left, each block (represented in red) is placed to fit the square. It will not be placed in an odd position as shown in the figure on the right.
Given four tetromino t_1, t_2, t_3, t_4, choose exactly three of them and place them in the desired position to determine if the block can be placed on the entire board.
However, all of the following conditions must be met before placing tetromino.
Blocks must not overlap.
Do not rotate a given tetromino.
For each i (1 \ leq i \ leq 4), do not use tetromino t_i more than once.
Each block of tetromino must not go out of the board.
Since n boards are given, make this judgment for each board and output Yes if the block can be placed on the entire board, and No if it is not possible.
Input format
t_1_1
t_2
t_3
t_4
n
B_1_1
...
B_n
First, you will be given the tetromino t_1, t_2, t_3, t_4 that you can use. Each t_i (1 \ leq i \ leq 4) is given in the following format:
h w
s_1
...
s_h
This is a rectangle of h x width w mass containing tetromino, and the shape of tetromino is represented by s_1… s_h. The part of the rectangle that represents tetromino is represented by #, and the other part is represented by .. Each rectangle contains exactly four #s. There is no row or column consisting only of ..
Next, the number of boards n is given. After that, n board faces B represented by 4 \ times 10 squares are given. The location where the block is located is indicated by #, and the location where the block is not is indicated by ..
Constraint
1 \ leq n \ leq 10 ^ 5
Each tetromino given does not violate the conditions mentioned above
There are exactly 28 #s on each board
For example, the following tetromino is not given.
3 3
.. #
. #.
..
(Some blocks are not connected, which does not meet the tetromino conditions mentioned above)
3 3
...
. #.
(The top line consists only of .)
Output format
Output over n lines. On the i-line, output the judgment result for board B_i as or.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
If the places where the tetrominoes corresponding to t_1, t_2, t_3, and t_4 are placed are indicated by 1, 2, 3, and 4, respectively, each board is laid out as follows.
3333 ##
444 ###
twenty four####
222 ###
11 #####
211 ####
222 ####
3333 ###
You can choose different tetromino for each board.
The second board cannot be covered with blocks due to the lack of ####.
Also, because you can't rotate tetromino, you can't lay down a third board.
Also note that there can be a way of arranging blocks like the 4th board. In other words, the board given by input is not necessarily the board made by combining tetromino.
We need to parse problem statement and solve. It's a problem about covering a 4x10 board with exactly 28 blocked cells (#). The board initially has 28 #, which are cells already occupied? Actually careful: "Now, consider the situation where blocks are placed on 28 squares on the board. As shown in the figure on the left, each block (represented in red) is placed to fit the square. It will not be placed in an odd position as shown in the figure on the right." Hmm.
Let me read the problem statement: It says (translated from Japanese): "Consider a board consisting of a rectangle with 4 squares x 10 squares. A square of 1x1 is called a block. Tetromino is a combination of four blocks, and there are the following seven types (and those that have been rotated 90 degrees arbitrarily)." Then: "Now, consider the situation where blocks are placed on 28 squares on the board. As shown in the figure on the left, each block (represented in red) is placed to fit the square. It will not be placed in an odd position as shown in the figure on the right."
This is ambiguous. Actually it might be: There is a board 4x10. Initially, there are 28 blocks placed on the board (i.e., 28 squares are filled). The goal: we are given four tetrominoes t1..t4. We must choose exactly three of them and place them (without rotation, each at most once) onto the board such that they cover exactly the 28 filled squares? Or do we need to fill the board entirely? It says: "Given four tetromino t_1, t_2, t_3, t_4, choose exactly three of them and place them in the desired position to determine if the block can be placed on the entire board." It might mean: we have to cover all the squares of the board (which is 4x10 = 40 squares) using the blocks? But then "blocks are placed on 28 squares on the board." Actually wait: The board has 4x10=40 squares. They say "consider the situation where blocks are placed on 28 squares on the board." That suggests that 28 squares are already occupied by blocks (perhaps given as input #). Then we are to take three of the tetrominoes (each tetromino consists of 4 blocks) and place them on the board, covering the empty squares? Because 28 occupied + 12 placed by three tetrominos = 40 total. Alternatively, maybe we need to cover the occupied squares with the tetrominoes? The phrase "to determine if the block can be placed on the entire board." Hmm.
Look at the examples. In example 1, the input: first the four tetrominos, then n=2, then board descriptions. The board descriptions: each board is given as 4 lines of 10 characters. They say "There are exactly 28 #s on each board." So the board has 28 # (occupied) and the rest '.' are empty.
Now output: "Yes" for board 1, "Yes" for board 2. They show how the tetrominoes (three of them) are placed, marking the cells with numbers 1,2,3,4 indicating which tetromino occupies that cell. The sample board: they show something like:
Board 1:
3333 ##
444 ###
twenty four####
222 ###
But this is not the raw board, it's the covering arrangement. The raw board presumably had 28 #, which after placing the three tetrominoes the entire board becomes filled? Actually they show numbers in some cells and # in others. But the board description in input for board 1 is:
But the sample input shown is messy due to line breaks. Let's reconstruct: In the problem statement, there's a section "入力例 1" and then some lines. It looks like:
But also there is an extra line ".." perhaps? Actually after the first two lines "2 3" and ".." and ".##" then "2 3" and ".." then "14" maybe? Let's check the text: "入力例 1
t2: 2x3
..
??? Wait there's "14" after that, maybe t3: 1x4? Actually 1 4? Then "####"? It's messy.
Let's look at output: They say "If the places where the tetrominoes corresponding to t_1, t_2, t_3, and t_4 are placed are indicated by 1,2, 3, and4, respectively, each board is laid out as follows.
3333 ##
444 ###
twenty four####
222 ###
11 #####
211 ####
222 ####
3333 ###"
Thus board 1 layout:
line1: "3333 ##"
line2: "444 ###"
line3: "twenty four####" -> maybe "24####"? Actually they wrote "twenty four####" which is probably "24####"? Wait "twenty four" maybe "24"? Possibly "24####" meaning two cells with tetromino2, then four cells with tetromino4, then ####? Actually it's ambiguous. But they show some pattern.
From the board input for board 1:
"####....##"
"####...###"
"####..####"
"####...###"
Wait that seems like 4 lines? Actually it's 8 lines? The board is 4x10, so there should be 4 lines per board. But the sample input shows after n=2, there are 8 lines? It shows:
That looks like 8 lines. But maybe it's just formatting; each line is 10 characters. The lines:
1: ".... ##" which likely is ".... ##"? Actually ".... ##" would be 6 chars? Let's count: ".... ##" -> 4 dots, space, # #? That is not correct. Probably it's ".... ##" meaning 4 dots, space, then two #? But it's messy.
Given the ambiguity, I'll rely on known puzzle: This is likely a problem about covering the 4x10 board with tetrominoes, but with a twist: The board initially has 28 filled cells (#), we need to choose 3 tetrominoes to place such that exactly all 28 filled cells are covered? Or such that after placement all cells become filled? In typical Tetris puzzles, you have a 4x10 board and you place tetrominoes to fill lines. But here the board has 28 #, meaning there are 12 empty cells. Each tetromino covers 4 cells, so three tetrominoes cover 12 cells. So we need to place three tetrominoes (chosen from the given four) exactly on the empty cells (.) such that after placement, the board is completely filled (all 40 cells become occupied). But the problem says: "determine if the block can be placed on the entire board." And the condition: "Blocks must not overlap." Also "Each block of tetromino must not go out of the board." Also "do not rotate a given tetromino." Also "For each i, do not use tetromino t_i more than once." So we choose exactly three tetrominoes from the four and place them on the board such that they cover all the empty squares (the '.' cells) and do not overlap with the existing '#' cells. Because the existing # are already placed blocks, we cannot place tetromino blocks on top of them. So we need to cover exactly the empty cells with three tetrominoes.
But is that the interpretation? Let's verify with sample 1: The board has 28 # and 12 '.'. The three tetrominoes (each 4 blocks) cover 12 cells, which are exactly the empty cells. So if we can place them without overlapping and without rotating, and each used at most once, then it's a Yes.
In the board arrangement they show: "3333 ##" etc. They label with numbers the positions where tetrominoes are placed. And the # are still shown as #. That means in the final board, the # are the original blocks, and numbers indicate the blocks from tetrominoes. So the board is filled with both # and numbers. So we need to place tetrominoes on empty cells.
Thus the problem: given four tetromino shapes (each 4 cells in a bounding box), each shape can be used at most once, and we must choose exactly three of them (any subset of size 3) and place them (without rotation) somewhere on the 4x10 grid, such that they do not overlap with each other nor with the pre-existing # cells, and they exactly cover all the empty cells (i.e., the union of the placed tetrominoes equals the set of '.' cells). Since the board has exactly 28 #, there are exactly 12 '.' cells. So we need to see if there is a selection of three tetromino shapes (distinct) and placements that exactly cover the '.' cells.
We must output Yes/No for each board.
Constraints: n up to 1e5. So we need an efficient solution per board, likely O(1) or O(some small constant) after preprocessing the tetrominos.
Given that the board is only 4 rows and 10 columns, the number of possible placements of a given tetromino is limited. The board is small: 4x10 = 40 cells. Each tetromino shape can be placed at various positions, as long as it fits within the grid. Since we cannot rotate, only translation. The number of possible placements for a shape of size h x w is (4 - h + 1) * (10 - w + 1). For each shape, at most maybe ~ (410)=40 placements? Actually maximum h is 4, w is up to maybe 4? Tetromino shapes: typical ones but they can be any shape? But constraints: Each tetromino given fits the description: exactly four cells, connected (by edges), no holes, and the bounding rectangle's first/last row and column are not all '.' (so no extra all-dot rows or columns). So h and w are between 1 and 4. So placements <= (4-1+1)(10-1+1) = 410 =40 at most, but for some shapes maybe up to 410=40? Actually if h=1 (a line of 4), then placements: (4-1+1)=4 rows? Wait 4 rows, height=1 => rows: 0..3 => 4 rows; width=4 => columns: 0..7 => 8 columns, so 32 placements. If h=4 (vertical line), rows: only 1? Actually height=4 => rows: 0? Only 1 row (0) because 4 rows total? Wait board rows are 4, so if shape height = 4, then row index can be 0 only. So (4-4+1)=1 row. width=1 => columns: 0..9 => 10 columns, so 10 placements. So overall placements for each shape is at most 32? Actually the max placements of a shape of 4 cells could be like a 2x2 shape (h=2,w=2) => rows 0..2 => 3 rows, columns 0..8 => 9 columns, so 27 placements. So each shape has at most maybe 40 placements? But 4*10=40, but not all shapes cover all cells. Anyway it's small.
We have 4 shapes total, but we only choose 3. So we need to check if there exists a combination of 3 distinct shapes (order doesn't matter, but placement matters) that exactly cover the '.' cells. Since board size is small, we could precompute for each board the set of empty cells (12 cells). Then we need to see if it can be partitioned into 3 tetromino placements (each placement covering 4 cells) such that each placement matches one of the shapes (without rotation) and shapes are distinct and chosen from the given four, using each at most once.
But n up to 1e5, we cannot do backtracking per board that explores many placements. However, the board is only 4x10, but the empty cells pattern may vary. We need to process many boards quickly. Possibly we can precompute all possible ways to cover the board's empty cells using three of the given tetromino shapes? But empty cells pattern varies per board. There are 2^40 possible boards, but only 28 #s fixed, so many patterns. However n up to 1e5, we need something efficient.
Maybe there is a trick: Since the board is only 4 rows, and tetrominoes are placed without rotation, the possible placements are limited. Perhaps we can treat each column or row? Alternatively, since the tetromino shapes are given and fixed, and we can choose any three, maybe we can reduce the problem to checking if the set of empty cells can be exactly covered by some combination of these shapes. This is like a tiling problem with three pieces on a small grid. Could use dynamic programming column by column (since width=10, height=4). That is common for such problems: DP over columns with state representing occupancy of current column and next few columns depending on shapes. Since we cannot rotate, but shapes can extend to the right? They have width up to 4. So DP with column index and mask of filled cells for the next few columns could work. But we also have to respect that we use exactly three tetrominoes, no more. And we have four possible shapes but we can only use each at most once, and we must use exactly three shapes (so we must choose a subset of three distinct shapes). So we need to assign shapes to placements. This adds a combinatorial dimension.
But maybe we can treat each shape as a tile and we need to tile the empty region with exactly these tiles (three of them, distinct). Since the empty region is exactly 12 cells, we need to place exactly three tiles. The number of ways to combine placements is limited. Possibly we can precompute all valid tilings of the entire 4x10 board with three tetrominoes? But wait the board has 40 cells; three tetrominoes cover only 12 cells, the other 28 are blocked. So we are not tiling the whole board; we are covering only a subset. But maybe we can think of the board as the complement of the blocked cells. We need to tile the '.' cells.
Because n is large, we need a fast decision algorithm. Possibly the answer is always Yes except for some patterns? But sample 2 shows both Yes and No cases.
Maybe the solution is to precompute all possible placements of the four shapes on a 4x10 grid, and then for each board compute the set of empty cells as a bitmask of 40 bits. Then we need to check if there exist three placements (with distinct shapes) whose union equals the empty mask and are disjoint. Since there are at most about 40 placements per shape, total placements across all four shapes maybe up to 160. Then the number of triples (choose 3 shapes from 4, and choose a placement for each) is at most: choose 3 shapes = 4 combinations; for each combination, number of triples placements: maybe up to (40^3) = 64k per combination, which is 4*64k=256k. That's not huge? Actually 40^3 = 64000, times 4 = 256,000. That's per board. But n=100,000, so total 25.6 billion, too much.
But we can reduce: for each shape, we can list placements that are subsets of the empty mask (i.e., all four cells are empty). Then we need to find three such placements with distinct shapes that exactly cover the empty mask. That is a set cover exact cover problem with small universe (12 bits) and few pieces. Since the empty mask has only 12 ones, each placement is a 4-bit subset. We need to partition the 12 cells into three groups, each matching a shape. This is like exact cover with 3 pieces. For a given board, the number of placements that fit (i.e., all cells empty) may be limited because empty cells are only 12. Typically, each shape might have many placements but only those entirely within empty region are candidates. Since empty region is small (12 cells), the number of candidate placements for each shape is limited. In worst case, empty region could be large? Actually empty region is exactly 12 cells, so any placement that contains a blocked cell is invalid. So the maximum number of placements per shape that lie entirely within a given set of 12 cells is not huge. But could be up to maybe the number of ways to place the shape within the convex hull of the empty cells. But worst-case if the empty region is e.g., a 4x3 rectangle, then for a shape like 2x2 there could be several placements. But still limited: the empty region has only 12 cells, so the number of distinct 4-cell subsets that match a shape and are within that region is bounded. In worst case, perhaps up to like 20 per shape? Actually, for a 4x3 empty region (12 cells), the number of placements of a shape could be counted. But overall, it's small.
Nevertheless, n=1e5, and per board we need to enumerate candidate placements and check for a partition. The naive approach of trying all triples from candidate placements of three shapes might be okay if candidate placements per shape are few (like <10). But worst-case could be higher? Let's consider worst-case empty pattern: maybe all 12 empty cells are in a contiguous block of 4x3. Many shapes can fit in many ways. For a 1x4 shape, there are 4 rows and columns? Actually in a 4x3 block, placements of a 1x4 shape: it requires 4 consecutive columns; if the block is exactly 4x3, columns 0-2, so 1x4 can't fit because need width 4 > 3. So shape sizes: each shape's bounding box dimensions up to 4. The empty region is only 12 cells, which might be arranged in many ways, but could be scattered. So likely the number of placements per shape within a given 12-cell set is at most maybe 10-20. Then triple combinations maybe up to 20^3 = 8000 per combination, times 4 = 32000. For n=1e5, that's 3.2e9 operations, too high.
We need a smarter method. Perhaps we can precompute all possible patterns of 12 empty cells that are coverable by three tetrominoes from the given set. Since the board is 4x10, the empty cells pattern is any subset of size 12. The number of such subsets is C(40,12) which is huge (~5e10). Not possible to precompute all.
But maybe we can use backtracking with pruning that is fast per board because 12 cells small. Could we do a simple DFS that tries to place tetrominoes one by one? At each step, pick an empty cell and try to cover it with each possible shape in each possible placement that fits. There are only 3 steps, and branching limited. That could be fast. For each board, we can perform a recursive search: we have a set of empty cells (positions). We need to place exactly 3 tetrominoes (using distinct shapes from the set of 4). So we can iterate over the 4 choices for which shape is omitted (i.e., choose which shape not to use). Then try to place the three chosen shapes in some order.
Simpler: Since we must use exactly three shapes, and the shapes are known, we can for each board try all permutations of three shapes (4 choices for omitted shape) and then try to cover the empty cells with those three shapes in some order. The search: we have a list of shapes (with fixed orientation). For each shape, we need to select a placement (position) that covers a subset of currently empty cells. After placing one shape, we remove its cells from the empty set, then try to place the next shape, etc. The third shape must exactly cover the remaining empty cells. So we can attempt to find a placement for shape A that is subset of empty set; then for shape B (distinct) a placement subset of the remaining; then check if the remaining cells exactly match some placement of shape C. That is O(number of candidate placements for A * candidate placements for B * maybe check C). But we can prune: Since the total number of placements for each shape is limited (say up to 40) and after filtering to only those fully within the initial empty set, it's still limited. So we can precompute for each shape the list of all possible placements (as bitmask of 40 bits) and store them.
For a given board, we compute empty_mask (40-bit). Then for each shape, we compute candidate masks = all placements whose mask is subset of empty_mask. That can be done by iterating over all placements for that shape and checking (mask & empty_mask) == mask. That's at most ~40 per shape, so ~160 checks per board, which is fine.
Then we need to check if there exists a triple (mask1 from shape i, mask2 from shape j, mask3 from shape k) such that they are pairwise disjoint and their union equals empty_mask. Since there are only 3 shapes, we can loop over combinations.
We can approach: For each omission (choose 3 shapes), we can try to find masks m1, m2, m3 from those shapes such that m1 | m2 | m3 == empty and are disjoint. Because we have only 3 shapes, we can do:
For the first shape, iterate over its candidate masks m1.
For the second shape, iterate over its candidate masks m2 such that (m1 & m2) == 0 and (m1|m2) is subset of empty.
Then let remaining = empty ^ (m1|m2). Then check if there exists a candidate mask for the third shape that exactly equals remaining. If yes, success.
Complexity per omission: For shape1 candidates count c1 (maybe up to ~40), for each, shape2 candidates filtered might be many, but we can pre-filter shape2 candidates to those that are disjoint with m1 and subset of empty. Could be up to c2 (maybe 40). So worst-case c1c2 = 1600. For each pair, we check if remaining is in set of masks for shape3 (precomputed as a hash set for quick lookup). That is O(c1c2). c1*c2 <= ~1600, times 4 omissions = 6400 per board. For n=1e5, that's 640 million operations, which might be borderline but possibly acceptable in optimized C++ (bit operations). But 640 million is high but might be okay if well optimized? However we also need to compute candidate lists per board, which adds overhead. Could be too slow for Python (which we might be using? The problem is from AtCoder? Possibly expects C++). But we are ChatGPT and need to produce a solution in some language? Usually we provide an explanation and maybe pseudocode. However the problem might be from JOI or something. But since we need to output an answer, we can produce a solution in Python and hope it's fast enough? 100k boards * 6400 = 640 million iterations, each simple bit ops and loops, likely too slow for Python. We need further optimization.
We could reduce the candidate placements per shape by precomputing for each shape all placements, but also maybe we can precompute all possible pairs of placements for two shapes? Not per board though.
But perhaps we can use meet-in-the-middle: For each omission, we could compute all possible unions of two shapes that are subsets of empty, then check if the complement is a placement of third shape. That's similar to above.
Alternatively, we can treat the problem as an exact cover with 3 pieces, but we could precompute all possible patterns of 12 cells that are tileable by any 3 of the 4 shapes (with each shape used at most once). Since the shapes are fixed, there might be a limited number of such patterns up to translation? But placements depend on board coordinates; the board is 4x10, so patterns are anchored. But we could precompute all possible unions of three placements (with distinct shapes) that are legal (i.e., placements don't overlap and fit within board). The total number of such triples might be manageable: each shape has up to ~40 placements, so total triples of distinct shapes (choose 3 shapes from 4) times placements could be up to (40^3)*4 = 256k, but many will overlap, so only those with disjoint placements and covering 12 cells exactly. The number of valid triples (each covering 12 distinct cells) might be less. For each such triple, we get a 40-bit mask representing the union of the three placements (i.e., the cells covered by the three tetrominoes). That mask has exactly 12 bits set (since placements are disjoint and each has 4 cells). So each triple yields a pattern of 12 occupied cells (the ones that would be covered by tetrominos). That pattern is exactly the set of empty cells we need to cover in the board. So if we precompute all possible empty masks that can be covered by three distinct shapes (from the given set) with no rotation, then for each board we just need to check if its empty mask is in that set. That's O(1) per board after preprocessing.
So the key is to generate all possible masks that can be formed by placing three distinct tetromino shapes (chosen from the four given) on the 4x10 board, without overlapping, each placed within board, and using each at most once. Since we must use exactly three shapes (so we omit one of the four), we need to generate all masks for each combination of three shapes. Then store them in a hash set (or boolean array of size 2^40? too large). But we can store as Python set of integers (bitmask). The number of such masks is limited. Let's estimate: For each combination of three shapes, number of triples of placements that are pairwise disjoint. Upper bound: For shape1 ~40 placements, shape2 ~40, shape3 ~40, total 64k combos. But many combos will have overlap, so only a fraction are valid. Could be up to maybe a few thousand? Actually, 12 cells out of 40, and each placement occupies 4 specific cells. The number of ways to tile 12 cells with three given shapes is limited. Possibly the total number of distinct masks across all combinations is not huge (maybe up to a few thousand or tens of thousands). That is manageable to precompute.
We then for each board, compute empty mask (bits for '.'? Actually careful: The board input has '#' for blocked cells, '.' for empty. The empty mask is the set of cells where '.' is present, i.e., where we need to place tetrominoes. So we compute a 40-bit integer where bit =1 for '.' cell (empty). Then check if that integer is in precomputed set. If yes, output "Yes", else "No". That would be very fast per board.
But we must ensure that we are exactly covering the empty cells, meaning the tetromino placements must not cover any blocked cell. In our precomputed masks, the mask is the set of cells covered by the tetrominoes (the placed cells). So if the board's empty cells match exactly that mask, then we can place tetrominoes there. So the condition is: empty_mask is one of the masks that can be exactly tiled by three distinct tetrominoes.
Thus the problem reduces to precomputing all possible tilings of the 4x10 board by three tetrominoes chosen from the given four, without rotation, each at most once. Since we don't consider rotation, but the shapes are given as is (they may be rotated versions already; we cannot rotate further). So we need to consider the shapes as given.
Edge case: Could there be multiple placements of the same shape used? No, each shape used at most once, so we only need to consider using each shape at most once. In a tiling, we use exactly three distinct shapes.
Now, precomputation steps:
Parse the four tetromino shapes. For each shape, given h and w, and a grid of h x w with '#' and '.', we need to extract the coordinates of '#' relative to top-left of bounding box. We'll store a list of shapes: each shape is a list of (dx, dy) offsets where # appears, with the minimal row and col being 0. Also store h and w for bounding box.
Generate all possible placements of each shape on the 4x10 board. A placement is defined by the top-left coordinate (r, c) such that 0 <= r <= 4-h, 0 <= c <= 10-w. For each (r,c), compute a bitmask of 40 bits: for each block of the shape, set the bit at position (r+dr, c+dc). We'll represent the board as 4 rows, 10 columns. Common mapping: bit index = r*10 + c. So mask is sum over blocks of 1 << ( (r+dr)*10 + (c+dc) ).
We'll store for each shape a list of masks (each a 64-bit integer). Also maybe store the list of placements with coordinates for debugging, but just masks needed.
For each combination of three shapes (i.e., choose which one to omit from the four), we need to generate all triples of masks (m1 from shape A, m2 from shape B, m3 from shape C) such that (m1 & m2) == 0, (m1 & m3) == 0, (m2 & m3) == 0. Then the union mask = m1 | m2 | m3. We'll store union mask in a global set (maybe also check that the union has exactly 12 bits set, which it will if disjoint). Also we might need to consider that the shapes are used exactly once; order doesn't matter, so we might generate duplicates across combinations? That's fine; we just add to set.
But careful: Could the same mask be generated by different shape combinations? That's possible, but we just need to know if mask is achievable. So we can store all union masks in a set.
Potential issue: The shapes might be such that two shapes are identical? The problem says tetromino t_i are given; they could be same shape? Possibly, as they are different tetromino types, but they could be the same shape? The condition "do not use tetromino t_i more than once" implies that if two t_i are identical, you still cannot use both because they are different indices. Actually the condition: "For each i (1 \ leq i \ leq 4), do not use tetromino t_i more than once." So you cannot use the same t_i twice, but you could use t_i and t_j even if they are identical because they are different tetrominoes? The problem says "choose exactly three of them". So if two are identical, you could choose both? The condition only says do not use a given tetromino more than once, it doesn't forbid using two different tetrominoes that happen to have the same shape. So it's allowed to use shapes that look the same if they are distinct t_i. However, note that the tetromino types are defined as the seven types and rotations, but they gave four specific ones. They could be same shape? Possibly not, but we should not assume they are distinct. So we treat each of the four shapes as distinct items, even if their shape patterns are identical. In that case, when we choose three of them, we need to consider which indices we omit. So we must generate combinations of indices, not shapes based on geometry. Because using shape A and shape B that are geometrically identical but different t_i would be allowed. So our precomputation must consider the identity of each tetromino (its index). So we have four shapes with possibly identical geometry. We'll generate placements for each shape separately.
Thus, for each combination of three indices (i.e., choose which one to omit: 0,1,2,3), we generate triples of masks (m_a, m_b, m_c) where a,b,c are the three indices in some order. Since the masks are from specific shapes, and we require the masks to be disjoint. The order doesn't matter for the union. So we can generate as follows: for each omission, we have three shape lists: L1, L2, L3. We'll iterate over placements from L1, L2, L3, ensuring disjointness. That will produce union masks that are achievable using those specific shapes (with those indices). That's fine.
Now the number of triples might be large if each shape has many placements. Let's estimate more concretely. The board is 4x10, each shape placements count:
For a shape of height 1 and width 4: placements: 4 rows * (10-4+1)=4*7=28? Actually width=4 => columns 0..6 => 7 columns, rows 0..3 => 4 rows, total 28.
Height 3, width 3: only if shape occupies a 3x3 bounding box (like T shape rotated?). But tetrominoes are only 4 cells, so bounding box can be up to 4 but 3x3 possible. Placements: rows: 4-3+1=2, cols:10-3+1=8, total 16.
Height 4, width 2: rows:1, cols:9 => 9.
Height 4, width 3: rows:1, cols:8 => 8.
Height 4, width 4: rows:1, cols:7 => 7.
Height 1, width 1? Not possible because 4 cells.
So maximum placements per shape is around 28 (for 1x4) or 27 for 2x2. So let's say up to 30.
Now for a given combination of three shapes, the total number of triples (m1,m2,m3) is up to 30^3 = 27,000. But we will filter for disjointness. That would be 27k per combination, times 4 = 108k triples to check. That's not huge. Actually 108k is quite manageable for precomputation (offline). Even if we do a naive triple nested loop (30^3) for each combination, that's 108k iterations, which is fine. But careful: for each combination, we need to iterate over all placements of shape1, shape2, shape3. That's 303030 = 27k. That's 108k total. That's trivial.
But we must also ensure that placements are within board and disjoint. However, we can generate all triples and check if masks are disjoint. That's 108k checks. That's perfectly fine for precomputation.
But we must also consider that some triples may produce the same union mask; we'll store in a set.
Thus, precomputation can be done easily. However, we need to be careful about the case where two shapes are identical and we use both; that is allowed as long as they are different indices. In our precomputation, we treat them as separate lists, so placements can be identical geometry but from different indices, and we still consider triples that might include both. That's fine.
Now, after we have the set S of all possible empty masks (i.e., union masks of three placements), for each board we compute its empty mask: for each cell (r,c) if char == '.' set bit. Then check if that mask in S. If yes, output Yes else No.
But wait: is it guaranteed that the board has exactly 28 #? Yes. So empty mask has exactly 12 bits. Our union masks also have exactly 12 bits (since three placements of 4 cells each, disjoint). So that matches.
Edge Cases: Could there be a scenario where the three placements are disjoint but they cover cells that are not all empty? But in our precomputation we are generating all possible placements irrespective of board. When checking a board, we compare the union mask to the empty mask. So if the union mask equals empty mask, then indeed those placements would fit exactly.
But we also need to ensure that we are not overlapping with the existing # cells. That's exactly satisfied because the union mask equals the empty cells.
Thus algorithm works.
Potential pitfalls: The board is 4x10, but our mask representation uses 40 bits. Must ensure ordering consistent.
Now, is there any nuance about the tetromino shape orientation? The problem says "do not rotate a given tetromino". So we use them as given.
Also, the board has exactly 28 #. So there are exactly 12 '.'.
Now, what about the condition "Blocks must not overlap." Already ensured by disjointness.
Also, "Each block of tetromino must not go out of the board." Our placements already restrict to within board.
Thus precomputation seems valid.
But we must also consider that we have exactly 4 tetrominos given, and we must choose exactly three. So we cannot use a tetromino twice, and cannot use all four. So our precomputation covers all subsets of size 3.
Now we need to consider if there is any other restriction: "Given four tetromino t_1, t_2, t_3, t_4, choose exactly three of them and place them in the desired position to determine if the block can be placed on the entire board." Possibly implies that we are to place them on top of the existing blocks? No, as reasoned, it's covering empty cells.
Let's double-check with sample 2 to ensure our interpretation matches. Sample 2 input:
Let's try to understand: The four tetrominos are: two 1x4 lines (####), and two 2x2 squares (##\n##). So we have two I-shaped (horizontal line?) Actually 1x4 means one row, four columns, so horizontal line of length 4. And two O-shaped (square). We must choose three of these four. So possible sets: either both I and one O, or both O and one I, or maybe one I and two O? But there are two I and two O, so choosing three could be: I, I, O (2 I's and 1 O) or I, O, O (1 I and 2 O). Not possible to take three all same because only two of each.
Now board 1: They output Yes. According to our approach, we would generate all unions of three placements (with distinct indices) and check. Should be Yes.
Board 2: No. Reason: "cannot be covered with blocks due to the lack of ####." Wait the explanation: "The second board cannot be covered with blocks due to the lack of ####." Possibly meaning there is no way to place a 1x4 tetromino because the empty cells are not arranged in a straight line of length 4? But our method would also detect that.
Board 3: No because rotation not allowed: "you can't lay down a third board." Might refer to some arrangement that would require rotating a tetromino which is not allowed.
Board 4: No because board is not necessarily made by combining tetrominoes: there could be a way of arranging blocks like the 4th board? Actually they say: "Also note that there can be a way of arranging blocks like the 4th board. In other words, the board given by input is not necessarily the board made by combining tetromino." That suggests that even if the board can be partitioned into three tetromino shapes in some way, we must use exactly the given tetrominos (with indices) and cannot rotate, so maybe the 4th board cannot be covered even though it looks like it could be tiled by some tetrominos (maybe including rotated ones). So our method would correctly check.
Thus the interpretation stands.
Now about performance: Precomputation: For each shape, generate placements (mask). Then for each combination (4 choose 3 = 4 combos), do triple nested loops over placements of the three shapes. That would be O(product of placements sizes). But we must ensure that we don't have too many placements per shape. Worst-case: shape1: 28 placements (I horizontal), shape2: 28 placements (another I horizontal), shape3: 27 placements (square). Then triple loops = 282827 ~ 21k. Times 4 combos = 84k. That's fine.
But note: If we have shapes with many placements, e.g., all four shapes are 1x4 horizontal lines, then each has 28 placements. For a combination of three such lines, we would have 28^3 = 21952 combos. For 4 combos, total ~88k. That's fine.
But careful: In the case of two identical shapes, when we generate triples for a combination that includes both identical shapes, we treat them as separate lists. So if both are I-lines, we will consider placements for shape A and shape B. That could produce many pairs that overlap or are identical? Overlap is fine we filter. But also we might double-count union masks? That's okay.
So precomputation is cheap.
Now, for each board we need to check membership in a set of masks. The set size might be at most number of triples we generate. Upper bound maybe a few thousand or tens of thousands. So membership test O(1) average.
Thus overall complexity: O(precompute) + O(n) for reading boards and checking.
Now we need to implement reading of tetrominos and boards. Input format: first 4 tetrominos, each described by h w and h lines of string. Then n, then n4 lines? But the sample shows after n there are 4n lines? Actually each board is 4 lines of 10 characters. So total lines after n is 4*n.
But the sample input 2 seems to show more lines: after n=4, there are 16 lines? Actually they show 4 lines for each board? They list 16 lines? Let's recount:
That's 1 + 4 boards * 4 lines = 16 lines? Actually after "4" there are 16 lines, yes. So that's correct.
Now potential nuance: The tetrominos might be given in a format where there are spaces? In sample 1 it shows "twenty three" etc. But we assume proper input: each line contains characters without spaces (except maybe between h and w). So we parse normally.
Implementation details:
Represent board as list of strings length 10.
Compute empty mask: iterate r from 0 to 3, c from 0 to 9, if board[r][c] == '.' then set bit (r*10 + c). Or if '#' then ignore. But careful: The board strings might contain spaces? In samples they show ".... ##" which suggests there might be spaces? But likely it's just a formatting issue in the problem statement; actual input lines have no spaces. So we treat them as strings of length 10.
For tetrominos: read h and w, then read h lines. Ensure that lines may have spaces? Probably not.
Now generate placements for a shape:
Given shape pattern: list of (dr, dc) coordinates relative to top-left where '#' exists. We'll compute offsets.
Procedure:
For each row i in 0..h-1, for each col j in 0..w-1, if grid[i][j] == '#', add (i, j) to list cells.
Then for each possible top-left (r,c) such that r in 0..4-h, c in 0..10-w:
mask = 0
for (dr, dc) in cells:
bit = (r+dr)*10 + (c+dc)
mask |= (1 << bit)
Append mask to list.
But careful: The shape cells must be exactly four, but we trust input.
Now we have for each shape index (0-3) a list of masks.
Now generate S:
Initialize set S = set().
For each combination (omit) in range(4):
indices = [i for i in range(4) if i != omit] # three indices
Let lists A, B, C = placements[indices[0]], placements[indices[1]], placements[indices[2]].
For mask1 in A:
For mask2 in B:
if mask1 & mask2: continue
mask12 = mask1 | mask2
For mask3 in C:
if mask12 & mask3: continue
union = mask12 | mask3
S.add(union)
But we can also optimize: since we iterate over all triples, it's fine.
But we might also want to consider that the order of shapes in the triple doesn't matter; however our loops will generate each combination of masks in a specific order. That's fine.
Potential duplicate unions across different omission combos: we add to same set.
Now, one subtlety: The problem states we must choose exactly three tetrominoes from the four. That means we cannot use a tetromino more than once, but can we use the same shape (if two indices have same shape) as two of the three? Yes, as discussed. So our generation for combination including both identical shapes is valid.
Now, is there any constraint about the tetromino being placed such that it cannot be placed in a way that some blocks are floating? Not relevant.
Now, we must ensure that the placements we generate are valid in the sense that the shape's blocks are connected? But input tetromino is guaranteed to be a valid tetromino (connected, no extra rows/cols). So that's fine.
Now, we should also consider that the board might have a pattern of empty cells that could be tiled in multiple ways; as long as at least one exists, we output Yes. So S contains all possible patterns that are tileable.
Now, verify that S includes only patterns that are exactly 12 bits. We'll check with popcount but not necessary.
Now, what about the scenario where the three placements are not disjoint but we use them to cover exactly the empty cells? Obviously they must be disjoint.
Now, implementation details in Python:
Use integers for masks (Python ints can handle up to 40 bits).
For generating placements, we may compute all masks and store as list.
For triple loops, we need to be careful about performance: triple loops up to ~30k per combo, total ~120k, which is trivial in Python.
But we also need to process up to 100k boards, each doing a simple set lookup, which is fine.
Thus solution should be efficient.
Potential memory: S size maybe up to maybe 10k-20k, fine.
Edge Cases: Could there be no possible union? Then S is empty, so all boards will be No.
Now, we should test with the given samples. But we need to reconstruct proper input format. However, we can trust that our solution would produce the sample outputs.
But we must be careful: In sample 1 output, both Yes. So S should contain the empty masks of those boards.
Now, one nuance: The tetrominos are given in some orientation; we cannot rotate them. In the sample, they show tetrominos:
t1: 2x3
..
.##
t2: 2x3
..
??? Actually need to parse correctly. But the exact shapes are not important; our algorithm will work.
Now, also note: The board is 4x10, but the tetromino shapes may have height up to 4, width up to 10? Actually width up to 10? But the shape's bounding box width could be up to 4 because it's a tetromino (4 blocks) and no extra rows/cols. Could it be width 5? For a shape like the S tetromino rotated? Typical tetromino bounding box at most 4 (since 4 blocks). So w <=4, h <=4. That's fine.
Now, what about shape with width 4 and height 2? That's possible e.g., T? Actually T in some rotation is 3x2? But width 4 and height 2 would be like a long shape? Actually a tetromino of 4 blocks cannot have both dimensions >2 if one dimension is 4? Example: I shape is 1x4 or 4x1. Z shape is 2x3. L shape is 3x2 or 2x3? L can be 3x2. O is 2x2. So max width is 4 (I horizontal), max height is 4 (I vertical). So w <=4, h <=4. So placements count is bounded.
Thus precomputation is small.
Now, let's think about possible pitfalls:
Input reading: The first line after each tetromino may have spaces? The format: "h w" on one line with space. Then h lines of length w. So we read as usual.
The board lines: each line is exactly 10 characters, maybe including newline. We'll strip newline.
n up to 1e5, we need to read efficiently, maybe use sys.stdin.read() and splitlines.
The board has exactly 28 '#' and 12 '.'; we can compute mask by iterating.
Now, one more nuance: In the problem statement, they mention: "Each block of tetromino must not go out of the board." Already ensured.
Now, do we need to consider that the tetromino shape must be placed such that its blocks align with the grid squares, i.e., integer positions. That's what we do.
Now, there might be a subtlety: When we place tetrominoes, they must be placed such that they do not overlap with each other or with existing blocks. In our S, we only consider placements that are disjoint. But we didn't consider the existing blocks because S is independent of board. Then for a given board, if the empty mask equals a union mask, then the placements used to generate that union mask would have all cells as empty, so they wouldn't overlap with any #. So it's valid.
But what about the case where the empty mask matches a union mask that used placements that in the original board are indeed empty, but some of those placements might also cover cells that are #? No, because the union mask equals the empty mask, so it's a subset of empty mask, so all cells in union are empty. So no overlap.
Now, check: Could there be a situation where the board's empty cells can be covered by three tetrominoes, but the specific tetrominoes we use are not the ones we precomputed because we might have multiple ways to cover, but our precomputed S includes all possible unions from any three distinct indices. So if there is any covering using three of the given tetrominos (with indices), then its union mask is in S. So it's correct.
Now, we must ensure that our triple loops do not miss any covering because we consider each combination of three indices, but we also need to consider that within those three indices, the order of placements is irrelevant. Our nested loops consider all permutations? Actually for a fixed combination of three shapes (indices i, j, k), we iterate over placements for shape i, then shape j, then shape k. That covers all assignments of placements to these shapes. Since the shapes are distinct indices, order matters because we assign mask1 to shape i, mask2 to shape j, mask3 to shape k. That's correct. But we also could have assignments where shape i gets a placement that could also be a placement of shape j (if shapes are identical). But since indices are distinct, it's okay.
Now, could there be a covering that uses shape A in a placement that is also a possible placement for shape B? That doesn't matter; we are assigning placements to specific indices. If we use shape A and shape B, both identical, we consider both assignments: shape A gets mask1, shape B gets mask2. That's correct. If there is a covering where shape A and shape B are swapped, both will be considered because when we loop, we consider all pairs (mask1 from A, mask2 from B). So both orders are covered.
Thus S includes all possible unions.
Now, what about the case where we use three shapes, but two of them are the same geometric shape but from different indices. Our precomputation includes that because we treat them as separate indices.
Now, potential optimization: Could there be an issue with duplicates causing large S? But it's fine.
Now, we need to handle input: first four tetrominos, then n, then n boards. But note that there might be extra blank lines? Usually not.
Now, let's implement.
Implementation Plan in Python:
Use sys.stdin.buffer.read().splitlines() to get all lines as bytes, decode? We'll use sys.stdin.read().split()? Better to use read().splitlines() and process.
But we need to parse integers and strings carefully. Since the input contains lines with dots and hashes, we can read all lines and iterate.
Simplify: Use sys.stdin.read().split() to get tokens? But the board lines have no spaces (should be contiguous strings), so split would treat them as tokens. That might work: tokens = sys.stdin.read().split() gives list of strings separated by whitespace. The tetromino h w lines: they are two integers. So we can parse sequentially.
Let's design: data = sys.stdin.read().split()
But careful: The tetromino lines (e.g., "..") are strings that might be just "..". That's fine. So we can parse with an index pointer.
Approach:
tokens = sys.stdin.read().split()
ptr = 0
Read four tetrominos:
for _ in range(4):
h = int(tokens[ptr]); ptr+=1
w = int(tokens[ptr]); ptr+=1
grid = []
for i in range(h):
s = tokens[ptr]; ptr+=1
# s should be of length w (maybe could be longer? but assume correct)
grid.append(s)
process shape: record cells.
Then n = int(tokens[ptr]); ptr+=1
Then for each board i in range(n):
board_lines = []
for r in range(4):
s = tokens[ptr]; ptr+=1
# s should be length 10
board_lines.append(s)
compute empty mask and check.
But note: The board lines are exactly 10 characters, and there might be lines like "....######" which is 10 chars. So tokens split by whitespace will give those strings. Good.
But what about lines that might contain spaces? In the problem statement, they show ".... ##" but that's probably formatting. I'll assume actual input has no spaces.
Thus using split() is fine.
Now, generating placements:
We'll store placements for each shape as list of ints.
Function gen_masks(cells, h, w):
cells: list of (dr,dc)
masks = []
for r in range(4 - h + 1):
for c in range(10 - w + 1):
mask = 0
for dr, dc in cells:
bit = (r+dr)*10 + (c+dc)
mask |= (1 << bit)
masks.append(mask)
return masks
But we might also want to store only unique masks? Could there be duplicate masks from different (r,c) due to shape symmetry? Possibly, but it's fine; we can keep duplicates as they are, but they'll cause duplicate checks in triple loops. To avoid duplicate work, we could deduplicate masks per shape. However, it's unlikely to have duplicates because different top-left produce different sets of bits. But for shapes that are symmetric, e.g., a 2x2 square: placing at (0,0) yields bits (0,0),(0,1),(1,0),(1,1). At (0,1) yields different bits. So not duplicates. Only if the shape is such that shifting yields same set? Not possible because grid is finite and positions are distinct. So no duplicates. So we can keep all.
Now, generate S:
S = set()
We'll have placements[0..3] lists.
for omit in range(4):
idx = [i for i in range(4) if i != omit]
A, B, C = placements[idx[0]], placements[idx[1]], placements[idx[2]]
for m1 in A:
for m2 in B:
if m1 & m2: continue
m12 = m1 | m2
for m3 in C:
if m12 & m3: continue
union = m12 | m3
S.add(union)
Now, after precomputation, we have S.
Now process boards:
For each board, compute empty_mask = 0
for r in range(4):
line = board_lines[r]
for c,ch in enumerate(line):
if ch == '.':
empty_mask |= (1 << (r*10+c))
Then check if empty_mask in S: print("Yes") else "No".
Now, potential edge: The board may have empty cells not contiguous or not exactly 12, but guaranteed 28 # so 12 '.'.
Now, complexity: Precomputation trivial, board processing O(n) with simple bitmask compute and set lookup.
Thus solution should work.
But we need to double-check if the union masks we generate indeed represent empty cells (the ones to be filled). Yes.
Now, one nuance: The board might have empty cells that can be covered by three tetrominoes but there might be multiple ways, including some that use a tetromino more than once? But we only allowed each at most once. Our S only includes unions from using each selected tetromino exactly once (since we choose exactly three indices and use each exactly once). That's correct.
Now, could there be a scenario where the same union mask can be achieved by different combinations of shapes? That's fine; we include it.
Now, is there any scenario where we need to consider that we can choose exactly three tetrominoes, but we might also have the possibility of using the same tetromino more than once if there are duplicate shapes? No, because the condition says "do not use tetromino t_i more than once". So even if two tetrominos are identical, we cannot use the same t_i twice. So our selection of three distinct indices is correct.
Now, what about the case where we have four identical shapes? Then we choose any three distinct indices; our precomputation will generate unions using three of them. That's valid because we are not using the same index twice.
Now, let's test with sample 2 manually to see if our method yields Yes/No accordingly. We'll trust.
Now, consider potential performance: In precomputation, the triple loops might be a bit heavy if placements per shape are ~30, but 30^3=27k per combination, total ~108k. That's fine.
But could there be shapes with more placements? For a shape of 1x4, placements = 4 rows * 7 columns = 28. For 2x2, placements = 3 rows * 9 columns = 27. For 2x3, placements = 3 rows * 8 columns = 24. For 3x2, placements = 2 rows * 9 columns = 18. For 3x3, placements = 2 rows * 8 columns = 16. For 4x1, placements = 1 row * 10 columns = 10. For 4x2, 19=9. For 4x3, 18=8. For 4x4, 17=7. So max 28. So product at most 2828*28=21952 per combo. So total < 90k. So very fast.
Now, we must also consider that we might need to generate placements for each shape. That is also trivial.
Now, implement.
But there's one more nuance: The tetromino shape may be given with empty rows/columns? The problem states: "There is no row or column consisting only of .'." So we have minimal bounding box. So h and w are the dimensions after stripping empty rows/cols? Actually they give h and w as the rectangle containing the shape; there may be no all-dot rows or columns, but there could be rows that have both # and ., and columns that have both. So the given h and w are the dimensions of the input. So we should not try to strip further; we just use the given h,w and coordinates of #.
Now, confirm mapping: For a shape, the relative coordinates (dr, dc) are the positions of # within the h x w grid. The shape is placed by aligning its top-left corner to (r,c). That will place the # cells at (r+dr, c+dc). That is correct.
Now, what about shapes that have "holes" or disconnected? The input guarantees it's a valid tetromino, so connected.
Now, the board is 4 rows, 10 columns. We must ensure that when we generate placements, we only consider positions where the shape fits entirely within the board: r from 0 to 4-h, c from 0 to 10-w.
Now, we also need to think about the possibility that the empty mask might have 12 bits but we might have generated a union mask that also has 12 bits but the placements might be overlapping with each other? No, we ensured disjointness.
Now, is there any scenario where the union mask has 12 bits but the placements are not disjoint? That can't happen because if they overlap, union would have less than 12 bits. So we require disjoint to get exactly 12 bits.
Now, all set.
Let's now consider potential memory/time for n=1e5: we read all boards, compute mask, set lookup, output lines. That's fine.
Now, I'll produce final answer.
But wait: The problem statement in Japanese might have an additional nuance: The board has blocks placed on 28 squares (red). The tetrominoes are placed to cover the rest? The statement: "Given four tetromino t_1, t_2, t_3, t_4, choose exactly three of them and place them in the desired position to determine if the block can be placed on the entire board." It might also be interpreted as we need to place the tetrominoes such that together with the existing blocks they fill the entire board (i.e., the tetrominoes fill the empty squares). That matches our interpretation.
Now, confirm with sample 1: They show covering with numbers and #. So indeed numbers are placed on empty cells.
Now, I think it's correct.
Now, we should also consider that the board may be given with # representing existing blocks. So our empty mask is '.'.
Now, maybe we should also verify with sample 2 board 4: They say "there can be a way of arranging blocks like the 4th board. In other words, the board given by input is not necessarily the board made by combining tetromino." That suggests that the board pattern might be such that it could be partitioned into three tetromino shapes in some way, but because the given tetromino set (with no rotation) doesn't allow that, it's No. So our method will correctly reject if the empty mask is not in S.
Now, let's think about potential pitfalls: Could there be a scenario where the empty mask can be tiled by three tetrominoes but using a different assignment of shapes to indices? That is covered.
Now, one nuance: The shapes are given as they are, but we might need to consider that they could be placed in flipped orientation? The problem says "and those that have been rotated 90 degrees arbitrarily." Actually that sentence: "Tetromino is a combination of four blocks, and there are the following seven types (and those that have been rotated 90 degrees arbitrarily)." This is describing the general concept of tetromino; but for the specific input, they give four tetromino shapes. It does not say we can rotate them; it says "Do not rotate a given tetromino." So we cannot rotate. So okay.
Now, we proceed.
Now, we need to output "Yes" or "No" for each board.
Edge Cases: n can be 0? But n >=1? The constraint says 1 <= n <= 1e5. So at least 1.
Now, finalize.
But we should test with a small custom case: Suppose the four tetrominos are all the same shape: 2x2 square. Then placements: each square occupies 4 cells in a 2x2 block. To cover 12 cells with three squares, we need three disjoint 2x2 blocks. On a 4x10 board, can we place three non-overlapping 2x2 squares? Yes, many ways. Our S would include unions of three disjoint 2x2 masks. So for a board with empty cells exactly those unions, it would be Yes. But if the empty cells are 12 cells that cannot be partitioned into three 2x2 squares (e.g., because they are not aligned in 2x2 blocks), then No. That's correct.
Now, implement.
Potential improvement: Since we use Python, set of ints with up to maybe 20k entries is fine.
Now, note: The board has 40 cells; we will use bits from 0 to 39. We'll define mapping: bit = r*10 + c, where r=0..3, c=0..9.
Now, for placements, we generate masks as ints.
Now, the triple loops: We need to be careful to avoid Python overhead of nested loops if we have many combos? But 108k is small. Even if we have 4 combos each with up to 30k iterations, that's 120k triple checks. That's negligible.
But wait: The triple loops will be: for m1 in A: for m2 in B: if m1 & m2: continue; for m3 in C: if (m1|m2) & m3: continue; add union. The innermost will be executed many times, but still <200k total. So fine.
Now, we might want to pre-filter placements for each shape? Not needed.
Now, one more thought: The union mask might have exactly 12 bits but we didn't check popcount; but since masks are from three placements each 4 bits and disjoint, popcount = 12 automatically. So no need.
Now, check that the placements lists are correct: We must ensure that for each shape, the cells we extract are exactly 4. Input guarantees that.
Now, we need to be careful about reading the tetromino lines: They may contain spaces? Possibly not.
Now, I'll produce final Python code.
But before finalizing, let's simulate sample 1 manually with code? Not possible here but we can reason.
Now, I'll write the solution.
Now, consider the possibility that the board may have spaces in lines? In problem statement example, they show ".... ##" which has a space; but that's likely formatting to indicate line break? Actually the input is presented in a monospaced font, and they might have split the line for display. In actual test cases, there will be no spaces. So we can ignore.
Now, implement.
Potential issues:
The input may have trailing spaces; we should strip each line when reading as token? Using split() will remove whitespace, so it's fine.
The tetromino grid lines might be given without spaces and of length w. So token length should be exactly w. If there are spaces within the line (like ". #."), that would break. But standard AtCoder problems don't have spaces. In the problem statement they show ". #." but it's likely they inserted spaces for readability? Actually in sample 2 they show ".#.#" which is fine. So I think it's safe.
The board lines are exactly 10 characters.
Now, we should also consider that the tetromino grid may have rows that are not all '.' and there may be spaces? I'll assume not.
Now, let's write code.
Pseudo-code:
import sys
def parse_shape():
h = int(tokens[ptr]); ptr+=1
w = int(tokens[ptr]); ptr+=1
cells = []
for i in range(h):
s = tokens[ptr]; ptr+=1
for j,ch in enumerate(s):
if ch == '#':
cells.append((i,j))
# generate placements
masks = []
for r in range(4 - h + 1):
for c in range(10 - w + 1):
mask = 0
for dr,dc in cells:
bit = (r+dr)*10 + (c+dc)
mask |= (1 << bit)
masks.append(mask)
return masks
def main():
data = sys.stdin.read().split()
ptr = 0
shapes = []
for _ in range(4):
h = int(data[ptr]); ptr+=1
w = int(data[ptr]); ptr+=1
grid_strs = []
for i in range(h):
grid_strs.append(data[ptr]); ptr+=1
# parse cells
cells = []
for i in range(h):
s = grid_strs[i]
for j,ch in enumerate(s):
if ch == '#':
cells.append((i,j))
# placements
masks = []
max_r = 4 - h
max_c = 10 - w
for r in range(max_r+1):
for c in range(max_c+1):
mask = 0
for dr,dc in cells:
bit = (r+dr)*10 + (c+dc)
mask |= (1 << bit)
masks.append(mask)
shapes.append(masks)
code
n = int(data[ptr]); ptr+=1
# precompute S
S = set()
# loop over omission
for omit in range(4):
idx = [i for i in range(4) if i != omit]
A, B, C = shapes[idx[0]], shapes[idx[1]], shapes[idx[2]]
for m1 in A:
for m2 in B:
if m1 & m2: continue
m12 = m1 | m2
for m3 in C:
if m12 & m3: continue
union = m12 | m3
S.add(union)
# process boards
out_lines = []
for _ in range(n):
board_strs = [data[ptr], data[ptr+1], data[ptr+2], data[ptr+3]]
ptr += 4
empty_mask = 0
for r in range(4):
s = board_strs[r]
for c,ch in enumerate(s):
if ch == '.':
empty_mask |= (1 << (r*10 + c))
if empty_mask in S:
out_lines.append("Yes")
else:
out_lines.append("No")
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
Now, test with sample input.
But we need to verify sample input format: It may contain extra lines or spaces. But our code expects exactly tokens: 4 shapes each with h w and h strings, then n, then 4*n strings.
shape2: h=2,w=2, s="##", next line "##"? Actually they gave "##" for two lines? Input shows:
2 2
Yes, cells: (0,0),(0,1),(1,0),(1,1) -> square, placements: rows 0..2 (max_r=2) rows 0,1,2? Actually 4-2=2, so rows 0,1,2? That's 3 rows? Wait: rows range(0, 4-2+1) => range(0,3) -> 0,1,2? Actually 4-2+1 = 3, yes rows 0,1,2? But height 2, so placing at row 2 would occupy rows 2 and 3, that's allowed. So 3 rows. Columns: 10-2+1=9 -> 0..8, so 3*9=27 placements. Good.
shape3: same as shape2, another 27 placements.
Now, S generation: For omit=0 (omit first I), we use shapes 1,2,3: one I and two squares. For omit=1 (omit second I), similar. For omit=2 (omit first square), we use I,I, square. For omit=3 (omit second square), similar. So S will contain unions from both configurations (two I's + one square) and one I + two squares.
Now, board 1 empty mask: The first board lines:
....
....######
..#.
..#.
But wait, the board lines after n=4: the first board is lines 1-4: "....", "....######", "..#.", "..#."? That seems 4 lines? Actually the list shows 16 lines: we need to group into 4-line boards. Let's group:
But line3 "..#." is 4 chars? That's not 10. There's inconsistency. Actually "..#." is 4 chars, but board width is 10. Something is off. Probably the board lines are 10 characters, but the formatting in the problem statement is messed up. In sample 2 they show:
It looks like each board might be represented by 4 lines, but some lines are broken into two? For example, the first board might be:
Row1: "...." but that's only 4 chars; maybe it's ".... "? No.
Perhaps the board input has spaces between characters? Like ". . . ."? But that would be 7 spaces? Not.
Maybe the input lines have spaces to separate groups? In the problem statement, they show ".... ##" meaning 4 dots, space, then two hashes? Actually ".... ##" could be "....##"? The space might be just to separate for readability. In sample 2 they have "....######" which is 10 chars: 4 dots + 6 hashes = 10. So that's fine. Then "..#." is only 4; maybe "..#." is actually "..#." plus something else? Could be "..#." then spaces? Not.
Let's look at sample 2 output description: They mention "lack of ####" for second board, and "you can't lay down a third board" etc. So the boards are presumably typical. I'll trust that the actual input format is correct.
Thus our code should work with proper input.
Now, one more nuance: The problem statement says "there are exactly 28 #s on each board." So we can rely on that.
Now, potential performance issue: The precomputation set S may contain many masks, but up to maybe 100k? Let's estimate upper bound.
For each combination, number of triples that are disjoint. The total number of disjoint triples might be less than the total placements product. For a given triple of shapes, the maximum number of disjoint triples can be estimated as: For each placement of shape1, the number of placements of shape2 that don't overlap is limited. In a 4x10 grid, the number of ways to place two disjoint tetrominoes of given shapes might be not huge. The product 30k is an upper bound, but many will overlap. So actual number of valid triples is smaller. So S size is likely a few thousand. So fine.
Now, we should also consider that we might generate the same union mask from different triples within same combination or across combinations. That's fine.
Now, test with extreme case: All shapes are 1x4 horizontal lines. Then we have 4 identical shapes. For a combination of three indices (three lines), we need to place three horizontal 1x4 lines on a 4x10 board without overlapping. How many ways? Each line occupies a row and a contiguous 4 columns. They must be placed in distinct rows? Actually they can be placed in same row if columns don't overlap? Since each line is 4 cells, two lines in same row could be placed in non-overlapping columns, e.g., one at columns 0-3, another at 4-7, etc. However, rows are 4. So the number of ways to place three horizontal lines without overlapping could be many. Let's count: We need to choose for each line a row (0-3) and a starting column (0-6) such that the segments don't overlap. Overlap occurs if same cell used by two lines. That could happen even if rows different? Overlap only if same row and overlapping columns; if rows different, they are disjoint automatically. So we can count: The number of ways to select three placements (ordered by indices) that are disjoint. This could be large. For three lines, the number of disjoint triples might be in the thousands. But still manageable. Even if it's 10k, it's fine. So S size maybe up to 10k.
Thus our approach is efficient.
Now, implement and produce final answer.
But before final, double-check if there is any catch: The board is 4x10, but the tetromino shapes may have cells that go beyond 4 rows if placed? No, we limit r to 4-h.
Now, consider if a shape has h=4, w=1 (vertical I). Then placements: r can be 0 only, c 0..9 => 10 masks. Good.
Now, the shape may be given with h=4 and w=4 but only four # cells. Example: a T shape that occupies a 3x3 bounding box, not 4x4. So h,w <=4.
Now, one more nuance: The problem says "do not rotate a given tetromino." But what about reflection? It doesn't say anything about reflection, so we cannot reflect either. So we place exactly as given.
Now, finalize.
Now, we need to produce final answer in the required format.
I'll write the solution explanation and then code.
But also, there is an alternative: Use backtracking per board which might be simpler but slower. However, precomputation is better.
Now, check if there's any possibility that the union masks we generate might not cover all possibilities because we assume that the three tetromino placements must be placed in some order and we consider all placements from the lists. But what about the possibility that two placements could be swapped between shapes? We already cover all assignments because we loop over all placements for each shape. So fine.
Now, also consider that the shapes are placed exactly once. There is no requirement that the shapes cannot be placed such that they are adjacent? No.
Now, we need to make sure that we treat the board as having rows 0..3 and columns 0..9. Our bit mapping: bit = r*10 + c.
Now, implement.
Potential improvement: Since n is large, we might want to precompute the empty mask for each board quickly by using bit operations on whole lines? But simple char loop is fine.
Now, I'll produce final code.
But we should also note that the input may have lines with trailing newline, but split() removes.
Now, final code:
python
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
shapes = [] # list of lists of masks for each tetromino
for _ in range(4):
h = int(next(it))
w = int(next(it))
grid = [next(it) for __ in range(h)]
cells = []
for r in range(h):
row = grid[r]
for c, ch in enumerate(row):
if ch == '#':
cells.append((r, c))
masks = []
max_r = 4 - h
max_c = 10 - w
for r in range(max_r + 1):
for c in range(max_c + 1):
mask = 0
for dr, dc in cells:
bit = (r + dr) * 10 + (c + dc)
mask |= 1 << bit
masks.append(mask)
shapes.append(masks)
n = int(next(it))
# Precompute all possible empty masks that can be covered
valid = set()
for omit in range(4):
idx = [i for i in range(4) if i != omit]
A, B, C = shapes[idx[0]], shapes[idx[1]], shapes[idx[2]]
for m1 in A:
for m2 in B:
if m1 & m2:
continue
m12 = m1 | m2
for m3 in C:
if m12 & m3:
continue
union = m12 | m3
valid.add(union)
out = []
for _ in range(n):
board = [next(it) for __ in range(4)]
mask = 0
for r in range(4):
row = board[r]
for c, ch in enumerate(row):
if ch == '.':
mask |= 1 << (r * 10 + c)
out.append("Yes" if mask in valid else "No")
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
We'll test with sample.
But there is a potential issue: The board lines may be given as exactly 10 characters, but our reading using split() will treat each line as a token. If a line contains spaces, split() would split it into multiple tokens, breaking the count. However, standard problems do not include spaces. In sample 2 they show lines like "....######" which is fine. If they had spaces, they'd be like ". . . ." but unlikely. So it's okay.
Now, also note: In the tetromino input, the lines may have length w exactly; but if they contain spaces? Probably not.
Now, check sample 1 input: It includes lines like ".." which are length 2. That's fine.
Thus solution is ready.
Now, we should produce final answer with explanation and code.
But we must also discuss the rationale in the solution explanation.
Now, I'll craft a final answer: description of algorithm, precomputation, etc.
Now, before finalizing, consider if there is any oversight: The problem says "choose exactly three of them and place them in the desired position to determine if the block can be placed on the entire board." Could it be that we must place the tetrominoes on top of the existing blocks to cover the entire board? That would mean we cover the # cells? That would be weird because they are already blocks, we wouldn't need to place blocks there. The typical puzzle is to fill the empty spaces. So our interpretation seems correct.
Also, the sample explanation shows numbers on the empty cells (since they show numbers and #). So numbers are placed on the '.' cells.
Thus final.
Now, I'll write final answer. We precompute all possible patterns of the 12 empty cells that can be exactly covered by three distinct tetrominoes chosen from the given four (without rotation, without overlapping, each used at most once).
Since the board is only 4×10, the number of placements per tetromino is at most 28, and the number of disjoint triples is at most a few tens of thousands – easily enumerable once before processing the queries.
For each of the four tetrominoes we generate all legal placements on the 4×10 board, represented as bitmasks (40 bits, one per cell).
Then for each subset of three tetrominoes (4 choices) we iterate over all triples of placements, keep those that are pairwise disjoint, and store the union mask in a global set S.
After this preprocessing, each query board (4 lines of 10 characters) is converted to a mask where a bit is set for every empty cell (.).
If that mask belongs to S we answer Yes, otherwise No.
The preprocessing is tiny (≤ 100 000 mask operations) and each query only needs a mask construction and a set lookup, so the overall complexity is linear in the number of boards, easily handling n ≤ 10⁵.
python
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
shapes = [] # list of lists of placement masks
for _ in range(4):
h = int(next(it))
w = int(next(it))
grid = [next(it) for __ in range(h)]
# coordinates of the four blocks inside the h×w rectangle
cells = []
for r in range(h):
row = grid[r]
for c, ch in enumerate(row):
if ch == '#':
cells.append((r, c))
# all placements of this shape on the 4×10 board
masks = []
max_r = 4 - h
max_c = 10 - w
for r in range(max_r + 1):
for c in range(max_c + 1):
mask = 0
for dr, dc in cells:
bit = (r + dr) * 10 + (c + dc)
mask |= 1 << bit
masks.append(mask)
shapes.append(masks)
n = int(next(it))
# precompute all feasible empty‑cell masks
feasible = set()
for omit in range(4): # choose which tetromino to omit
idx = [i for i in range(4) if i != omit]
A, B, C = shapes[idx[0]], shapes[idx[1]], shapes[idx[2]]
for m1 in A:
for m2 in B:
if m1 & m2:
continue
m12 = m1 | m2
for m3 in C:
if m12 & m3:
continue
feasible.add(m12 | m3)
out = []
for _ in range(n):
board = [next(it) for __ in range(4)]
mask = 0
for r in range(4):
row = board[r]
for c, ch in enumerate(row):
if ch == '.':
mask |= 1 << (r * 10 + c)
out.append("Yes" if mask in feasible else "No")
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()