We need to count number of ways to build a wall of height N and width M using blocks of lengths 1,2,3,4 (all 1x1xk, essentially 1x1xL horizontally placed). Blocks can only be placed horizontally. So each row of height 1 (since blocks have height 1? Actually block sizes are (1x1x1), (1x1x2), (1x1x3), (1x1x4). So they are all 1 in height? Yes, height is 1, depth is 1, width is length. So they are like bricks of height 1, depth 1, and width L. So the wall is built by stacking rows of height 1, each row is composed of horizontal bricks that cover the width M exactly without gaps. The rows are stacked on top of each other to total height N. So each row is a tiling of a 1xM line using tiles of lengths 1,2,3,4.
But the condition of "solid structure" means that there should be no vertical line that goes from top to bottom without cutting any brick. That is, the wall should have no vertical crack that goes through all rows. In other words, the joint patterns between bricks in consecutive rows should be such that for every vertical line at a fraction (between integer positions?), the gaps between bricks (the boundaries) should not align across all rows. More precisely: "You cannot make a vertical cut from top to bottom without cutting one or more lego blocks." This means there should be no straight vertical line (with integer coordinate? Typically, we consider positions from 0 to M, and blocks occupy intervals of integer length. The vertical cut is a line at a certain x-coordinate (non-integer? Actually if blocks have width integer, the boundaries between blocks occur at integer positions from 1 to M-1. If we cut exactly at an integer position, it might pass through the gap between blocks if there is a gap. But the wall is solid if there is no vertical line (any x coordinate between 0 and M) that can be drawn without intersecting any block across all rows. However, typically in such problems (like brick wall patterns), the condition is that the wall should not have a straight line from top to bottom that goes through the gaps between bricks. Usually, the vertical lines considered are at integer positions (the boundaries between unit cells). Because bricks are of unit squares? But here bricks are of width L, covering L unit cells horizontally. The wall is of width M (an integer number of unit cells). So we can think of the wall as an N x M grid of 1x1 cells (since bricks are height 1 and depth 1, but we ignore depth). Each brick covers a contiguous set of cells in a row. The condition is that there should be no vertical line that goes from the top to the bottom through the gaps between bricks (i.e., through the edges that separate cells?). If we think of vertical cuts at integer positions between columns, then a cut at position k (between column k and k+1) will pass through gaps if every row has a brick boundary at that same position (i.e., the break between two bricks). Also a cut at position 0 (left edge) or M (right edge) would always be at boundary? Usually the wall edges are not considered because you could cut there but that's the boundary of the wall. The problem likely means no internal vertical line that separates the wall into two parts without cutting bricks. So we need to count the number of ways to tile an N x M board with horizontal bricks of lengths 1,2,3,4 such that there is no vertical line (between columns) that goes through all rows without intersecting any brick.
This is a classic problem: "Number of ways to build a wall without vertical cracks" similar to "brick wall" problems. Usually we compute total number of tilings of rows independently: total ways = (W)^N, where W = number of ways to tile a 1xM row with given lengths. Then subtract those where there is at least one vertical line (between columns) that is a crack across all rows. But careful: multiple cracks can exist, so need inclusion-exclusion. Another approach: use recurrence for solid walls: Let F(M) be number of ways to tile a single row (width M) with given brick lengths. Then total arrangements of N rows without restriction is F(M)^N. The condition of no vertical crack that goes through all rows is equivalent to that for each column separation (1..M-1), not all rows have a break at that position. So we need to count N-row configurations where there is no column separation where all rows have a break.
However, it's not just "break at a column separation" because a row may have a brick that spans across that separation, thus that separation is not a break (i.e., the vertical line would cut through that brick). So for each row, a particular vertical line at position k (between column k and k+1) will be "clear" (i.e., not cutting a brick) if and only if the row has a brick boundary at that position (i.e., the cut aligns with the gap between bricks). If the row has a brick covering both columns k and k+1, then the cut would cut that brick. So the condition for a valid wall: For every k in {1,...,M-1}, there exists at least one row where the cut at k would cut a brick (i.e., that row does NOT have a brick boundary at k). Equivalent: there is no k such that all rows have a brick boundary at k.
Thus we need to count the number of N-row tilings (each row is a tiling of width M) such that for each k=1..M-1, at least one row does not have a boundary at k.
But note: The wall is built by stacking rows. The rows are independent except for this global condition. So we can compute using principle of inclusion-exclusion over the set of "bad" columns: for each subset S of {1,...,M-1}, count number of N-row tilings where every row has a boundary at each k in S. Then inclusion-exclusion yields number of tilings with no such S= all columns bad.
Number of rows where each row must have boundaries at all positions in S. For a fixed set S, we need to count number of tilings of a single row that have boundaries at those positions. Then raise to Nth power, then sum over subsets with sign.
But careful: boundaries must be at integer positions; having a boundary means that between column i and i+1 there is a division between bricks. That is, the row's tiling must be such that each brick covers a contiguous set of columns, and the boundaries occur at some subset of {1,...,M-1}. For a given set S, we require that the row's tiling includes all those boundaries (i.e., the row is composed of bricks that break at each of those positions). However, can a row have boundaries at positions that are not aligned with brick edges? Actually the brick edges are exactly the boundaries. So a row's tiling determines a set of boundaries B (subset of {1,...,M-1}). The condition that the row has boundaries at all positions in S means S ⊆ B. That is, the row's tiling must break at those positions (i.e., no brick spans across them). But note: If we force a boundary at position k, it means that the row cannot have a brick covering both column k and k+1. This imposes constraints on the tiling: the row must be composed of bricks that are placed such that each brick lies entirely within the segments defined by S. Essentially, S partitions the width into segments (intervals). Let the segments be of lengths L1, L2, ..., L_{|S|+1} where these lengths sum to M. For the row to have boundaries at all positions in S, the tiling must exactly tile each segment independently (with bricks), and there must be no brick crossing segment boundaries because boundaries are enforced. However, is it sufficient that S ⊆ B? Could there be additional boundaries? Yes, the row can have extra boundaries beyond S. That's allowed. But if we require that the row has boundaries at all positions in S, it doesn't require that there are no boundaries elsewhere; it's just that at those positions, there must be a boundary. So the row's tiling must be such that it does not have a brick crossing any k in S. That means the row can be considered as tilings of the segments determined by S, but also possibly with additional internal boundaries within each segment. However, note that if we treat each segment as a sub-width, any tiling of that segment with bricks will naturally not cross the segment boundaries? Actually the segment boundaries are at positions that are forced to have a boundary; but if we tile each segment independently, the tilings within a segment may have boundaries inside the segment, but they won't cross the segment boundaries because the segment boundaries are at the edges of the segment. So any tiling of the whole row that does not have bricks crossing S is equivalent to independently tiling each segment (with the same brick lengths). And yes, any such tiling will have boundaries at S? Not exactly: If we tile each segment independently, the bricks will start and end at the segment boundaries? The segment boundaries are at positions that are the ends of segments. For a segment from a to b (columns a+1 to b, say), the left boundary is at position a (which is a forced boundary) and the right boundary is at position b (forced). When we tile that segment with bricks, the bricks will be placed within that segment; they will not cross the left or right boundaries because they are confined to that segment. At the left boundary (position a), is there necessarily a boundary in the row? Yes, because the segment starts there; the leftmost brick starts at column a+1, so between column a and a+1 there is a boundary. However, what about the right boundary? The segment ends at column b. The last brick ends at column b. Between column b and b+1 there is a boundary (since next segment starts at b+1). So indeed, tiling each segment independently yields a row that has boundaries exactly at all positions in S plus possibly some internal boundaries. Conversely, any row that has boundaries at all positions in S can be seen as a concatenation of tilings of the intervals between S. So the number of row tilings that have boundaries at all positions in S is equal to the product over segments of F(L_i), where F(L) is the number of tilings of a 1xL row with bricks of lengths 1-4. Wait: But F(L) counts all tilings of width L, which may have internal boundaries. That's fine. And the product gives all ways to tile each segment independently. So yes.
Therefore, for a fixed S, the number of rows that satisfy S ⊆ B is: G(S) = ∏_{segments} F(length of segment). And then number of N-row configurations where every row has boundaries at all positions in S is G(S)^N.
Then by inclusion-exclusion, the total number of valid walls (with no column where all rows have a boundary) is:
Valid(N,M) = Σ_{S ⊆ {1,...,M-1}} (-1)^{|S|} (∏_{segments defined by S} F(L))^N
But note: This sum includes S = empty set, where the product is just F(M) (since one segment of length M), and sign positive, so that's the total number of tilings without restriction, F(M)^N. Then subtract those with at least one column fully boundary, etc.
However, there is a subtlety: The condition "cannot make a vertical cut from top to bottom without cutting one or more lego blocks" might also consider cuts that go through a brick? Actually the phrase: "should not be possible to separate the wall along any vertical line without cutting any lego block". So we want that any vertical line (presumably any x coordinate) will intersect at least one brick in at least one row? Wait careful: If there is a vertical line that does not cut any block in any row, then it would be possible to separate the wall along that line without cutting blocks. So we need that for every vertical line, there exists at least one row where the line cuts a block (i.e., passes through a brick). Equivalent to: there is no vertical line that passes only through gaps between bricks in all rows. But could there be a vertical line that goes through a brick in some rows but not all? That's fine because then you would have to cut that brick to separate the wall? Actually if there is any brick intersected, then to separate along that line you would need to cut that brick. So the wall is solid if there is no line that avoids all bricks across all rows.
Now what about lines that are not at integer boundaries? If a line is at a non-integer x coordinate (like 1.5), then it will always cut through the interior of unit cells? But bricks are composed of unit cells? The bricks are solid; if placed on a grid, a vertical line at non-integer x will pass through the interior of a unit cell column? Actually consider a row of unit squares (cells) of width 1. The bricks occupy a set of contiguous cells. A vertical line at x = k+0.5 (between the centers) will pass through each cell? Typically, if we think of the cells as squares from 0 to M, a line at x = c can pass through a brick if the brick's x-interval contains c. If c is not aligned with the boundaries, then it may be inside a brick if that brick covers that interval. However, the important point is: If there exists a vertical line that never cuts any brick, that means for each row, the line falls entirely within a gap between bricks. But gaps between bricks are at the boundaries between cells (integer positions). Actually a gap is a vertical line of zero thickness between two adjacent bricks. If the line is exactly at an integer position, it can pass through the gap. If it is slightly off, it would intersect one of the bricks. So the only potential "clear" lines are exactly at integer positions (between columns). However, one could also consider lines that go through the interior of a cell that is part of a brick? That would cut the brick. So the only lines that could avoid bricks are those that align with the boundaries between bricks. So it suffices to consider integer positions 1,...,M-1. So the condition reduces to: No column gap where every row has a boundary. That matches typical interpretation.
Thus inclusion-exclusion is valid.
Now we need to compute for N,M up to 1000. The number of subsets of columns is huge (2^{M-1}) so direct inclusion-exclusion is impossible. However, the product ∏ F(L_i) depends only on the lengths of segments defined by S, not on the specific positions? Actually the segments lengths are determined by the positions in S. But S is a subset of {1,...,M-1}; the segments lengths are the distances between consecutive selected boundaries plus the ends. So the product is ∏ F(L_i) where the L_i are the lengths of intervals between consecutive elements of S (including before first and after last). So essentially, for a given S, the product is determined by the multiset of lengths of intervals. But we can perhaps use DP to compute sum over subsets. There is known technique: The number of solid walls (no vertical crack) can be computed via generating functions or recurrence. Actually there is a known problem "LEGO Blocks" on HackerRank that asks exactly this. I recall that solution involves computing total tilings per row, then using inclusion-exclusion via DP with modular arithmetic and exponentiation, or using a principle of "connected" tilings across rows. Another approach: Let A = number of ways to tile a single row (F(M)). Then let B = number of ways to tile a wall of height N without restriction = A^N mod MOD. But we need to subtract those with at least one vertical line of weakness. Usually one uses recursion: Let g(N, M) = number of ways to build a wall of height N and width M that is solid (i.e., no vertical crack). Then one can derive g(N,M) = total(N,M) - sum_{k=1}^{M-1} (something). I think there is a known recurrence: Let f(M) = number of tilings of a single row. Compute f via DP (since M up to 1000, with tile lengths 1,2,3,4, easy). Then let total(N,M) = f(M)^N mod MOD. But then we need to subtract "bad" walls: those that can be split vertically into two independent solid walls? Actually we can think of the first place from the left where a vertical crack occurs. But need to be careful: The condition "no vertical crack that goes through all rows" is equivalent to the wall being not separable into two subwalls without cutting bricks. So we might decompose by the leftmost column where there is a crack through all rows. However, if there is a crack at some column, that crack splits the wall into two parts that are independent (since there is no brick crossing that column across any row). But these two parts themselves might have internal cracks. For the wall to be counted as "bad", we need that there is at least one such column. But when we subtract, we must avoid overcount.
One method: Count solid walls via recurrence using the concept of "connected" tilings across width. Let g(N,M) be the desired solid count. Then total(N,M) = f(M)^N. But any wall (possibly with cracks) can be decomposed by considering the first column from the left where a crack exists across all rows. Let's define for a given wall, consider the smallest k (1 ≤ k < M) such that there is a crack at column k (i.e., all rows have a boundary at k). If there is no such k, the wall is solid. If there is such a k, then the wall can be thought of as a left part of width k and a right part of width M-k, each being some wall (the left part may have cracks, but note: The left part's rightmost boundary is at k, but does the left part have a crack at its right edge? Actually the wall's left part is columns 1..k. Since there is a crack at k across all rows, the left and right parts are independent: no brick spans across. However, the left part itself may have its own cracks, but it might be any wall (solid or not) of width k. Similarly the right part of width M-k. But careful: The left part, considered as a wall of width k, might have cracks at its own interior. That's allowed. So the set of walls that have a crack at some column k (and possibly others) can be partitioned by the first such column from left? However, there could be multiple cracks; the "first" crack is the smallest k where the crack occurs across all rows. Then the left part (width k) must be solid? Not necessarily: It could have a crack at some column j < k that goes through all rows? But if there were such a crack at j, then j would be a crack and j < k, contradicting that k is the smallest. So indeed, if k is the smallest column with a full crack, then the left part (width k) must have no full crack, i.e., it is solid. Because if it had a full crack at j<k, that would be a smaller crack. So the left part is a solid wall of width k. The right part can be any wall (including cracks) of width M-k, because we don't care about cracks there. However, there is also the possibility that there is a crack at k but no smaller crack; then the whole wall is not solid. So we have:
Total(N,M) = g(N,M) + Σ_{k=1}^{M-1} (g(N,k) * Total(N, M-k))? Let's verify.
We consider all walls of height N and width M (total(N,M) = f(M)^N). Among these, some are solid (g(N,M)). Others are not solid, i.e., have at least one full vertical crack. For each non-solid wall, consider the smallest column k where a full crack occurs. Then:
- The left part (columns 1..k) is a solid wall: because if it had a full crack at some j<k, that would be a smaller full crack. So left part is solid.
- The right part (columns k+1..M) can be any wall (including those with full cracks) because after the crack at k, there is no restriction from the left; the right part is independent and can be any configuration of width M-k (since rows are independent? Actually careful: The rows are independent across the whole width, but the condition that there is a full crack at k means that every row has a boundary at position k. This implies that the tiling of each row is the concatenation of a tiling of width k and a tiling of width M-k, with no brick crossing. So the entire wall can be seen as: for each row, we choose a tiling of left segment (width k) and a tiling of right segment (width M-k) independently. So the whole wall is determined by the choices of left tilings for all rows (forming a wall of width k) and right tilings for all rows (forming a wall of width M-k). The left wall is exactly a configuration of height N and width k, but does it have to be solid? As argued, since k is the smallest full crack, the left part cannot have any full crack, i.e., it is solid. The right part can be any configuration (including those with full cracks) because there is no condition about being smallest on that side. However, note: Could the right part have a full crack that aligns with the left part's full crack? That's fine; but the smallest full crack of the whole wall is k, so any full crack in the right part would be at columns > k, which are allowed. So the right part can be any wall of width M-k, solid or not. Therefore, for each k, the number of walls where the smallest full crack is exactly at k is: g(N,k) * Total(N, M-k). Because:
- For left part: number of solid walls of height N, width k = g(N,k).
- For right part: any wall of height N, width M-k = Total(N, M-k) = f(M-k)^N.
But careful: Are left and right parts independent? In each row, the left tiling and right tiling are independent given the widths. So overall number of configurations where there is a full crack at column k and no full crack at any column < k is: (number of solid walls of width k) * (total number of walls of width M-k). However, is it guaranteed that the crack at k exists across all rows? In the concatenation, because we are combining a tiling of width k and a tiling of width M-k, we automatically have a boundary at the join (position k) in each row? Actually if we take a left tiling of width k and a right tiling of width M-k, we must ensure that they are placed adjacent, but there will be a boundary at position k (the end of the left tiling and start of right). Since the left tiling covers columns 1..k, it ends at column k. The right tiling starts at column k+1. So at the interface between column k and k+1, there is a boundary. However, note that the vertical line considered is between column k and k+1. That line will pass through the gap between bricks in that row. So indeed, if we concatenate two tilings, we get a boundary at that position. So the concatenation always yields a full crack at k? Yes, because every row will have a boundary at that position because the left and right tilings are separate. So any configuration formed by combining a left wall and a right wall via concatenation automatically has a full crack at column k. But is it possible to have a configuration that has a full crack at k but is not representable as concatenation of independent left and right walls? If every row has a boundary at k, then each row's tiling can be split into a left tiling of width k and a right tiling of width M-k. So yes, it's exactly that representation. So the mapping is bijective: configurations with a full crack at k correspond to pairs (left wall, right wall) of widths k and M-k. So number of configurations with a full crack at k is Total(N,k) * Total(N,M-k). But that's not what we want for smallest crack. Because that counts all configurations with a crack at k, regardless of whether there is also a crack at some smaller column. In the recurrence for solid walls, we want to subtract those that have any crack. So we need to partition the set of non-solid walls by the smallest crack.
Thus we have:
Total(N,M) = g(N,M) + Σ_{k=1}^{M-1} [ number of walls where the smallest full crack is at k ].
And number where smallest full crack is at k = g(N,k) * Total(N, M-k). Because left part must be solid (no crack), right part can be anything. But is right part truly any wall? The right part is of width M-k, and we concatenate left solid wall and right any wall. That yields a wall that has a full crack at k, and no full crack at any j<k because left is solid. However, could there be a full crack at some j>k that also goes through? That's allowed; it doesn't affect smallest. So yes.
Thus we have:
g(N,M) = Total(N,M) - Σ_{k=1}^{M-1} g(N,k) * Total(N, M-k).
But is this correct for all M? Let's test with sample.
First compute f(M) for small M with tiles 1,2,3,4. Recurrence: f(0)=1 (empty tiling), f(negative)=0. f(m) = f(m-1)+f(m-2)+f(m-3)+f(m-4). For M=1: f(1)=1 (only 1-length). Actually f(1)=1? With tile length 1, yes. f(2): f(2)=f(1)+f(0)=1+1=2? Also length 2 tile directly gives 1, plus two 1's gives 1, total 2? Wait careful: tiling 1x2: either one tile of length 2, or two tiles of length 1. So 2 ways. f(2)=2. f(3): possibilities: 1+1+1; 1+2; 2+1; 3. So 4 ways. f(3)=4? Let's compute recurrence: f(3)=f(2)+f(1)+f(0)=2+1+1=4. Yes. f(4): tiles: all 1's; 1+1+2 (3 permutations? Actually 1+1+2, 1+2+1, 2+1+1); 1+3; 3+1; 2+2; 4. So count: 1 (all 1) + 3 (two 1 and one 2) + 2 (1+3) + 1 (2+2) + 1 (4) = 8? Let's compute recurrence: f(4)=f(3)+f(2)+f(1)+f(0)=4+2+1+1=8. Yes.
Now total(N,M) = f(M)^N.
Now compute g(N,M) from recurrence: g(N,1) = total(N,1) because width 1 cannot have any internal vertical line (since M-1=0, no crack possible). So g(N,1)=f(1)^N = 1^N = 1.
For M=2:
g(N,2) = total(N,2) - Σ_{k=1}^{1} g(N,k) * total(N,2-k) = f(2)^N - g(N,1)total(N,1) = (2^N) - (1)(1^N) = 2^N - 1.
Check sample: For N=2, M=2: 2^2 -1 =4-1=3 matches output 3.
For N=3, M=2: 2^3 -1 =8-1=7 matches output 7.
Good.
For M=3:
We need g(N,3) = total(N,3) - [k=1: g(N,1)*total(N,2) + k=2: g(N,2)*total(N,1)].
total(N,3)=f(3)^N = 4^N.
g(N,1)=1.
total(N,2)=2^N.
g(N,2)=2^N -1.
total(N,1)=1.
So g(N,3) = 4^N - (1 * 2^N + (2^N -1)*1) = 4^N - (2^N + 2^N -1) = 4^N - (2^{N+1} -1) = 4^N - 2^{N+1} + 1.
Test N=2: 4^2=16, 2^{3}=8, 16-8+1=9. Sample output for (2,3) is 9. Good.
N=3: 4^3=64, 2^{4}=16, 64-16+1=49. Not in sample but could check.
For M=4:
g(N,4) = total(N,4) - Σ_{k=1}^{3} g(N,k)total(N,4-k).
total(N,4)=f(4)^N = 8^N.
k=1: g(N,1)total(N,3)=1 * 4^N = 4^N.
k=2: g(N,2)total(N,2)= (2^N -1) * 2^N = 2^N(2^N -1) = 2^{2N} - 2^N.
k=3: g(N,3)total(N,1)= (4^N - 2^{N+1} + 1) * 1 = 4^N - 2^{N+1} + 1.
Sum = 4^N + (2^{2N} - 2^N) + (4^N - 2^{N+1} + 1) = 2^{2N} + (4^N+4^N) + (-2^N - 2^{N+1}) + 1 = 2^{2N} + 24^N - (2^N + 2^{N+1}) +1.
Now 4^N = 2^{2N}, so 24^N = 22^{2N}= 2^{2N+1}. So sum = 2^{2N} + 2^{2N+1} - (2^N + 2^{N+1}) +1 = 32^{2N}? Wait 2^{2N} + 2^{2N+1} = 2^{2N}(1+2)=32^{2N} = 34^N. Actually 2^{2N}=4^N, so sum = 4^N + 24^N? That's 34^N? Let's recalc: 2^{2N} = 4^N. 2^{2N+1}=24^N. So sum = 4^N + 24^N = 34^N. Then subtract (2^N+2^{N+1}) = 2^N + 22^N = 32^N. Then +1. So sum = 34^N - 32^N + 1.
Thus g(N,4) = 8^N - (34^N - 32^N + 1) = 8^N - 34^N + 32^N - 1.
Check for N=4: 8^4=4096, 4^4=256, 3256=768, 2^4=16, 316=48, so 4096 - 768 + 48 - 1 = 4096 - 768 = 3328, +48 = 3376, -1 = 3375. Sample output for (4,4) is 3375. Good.
So recurrence works.
Thus we have a DP solution: Precompute f[1..1000] for row tilings. Then for each N,M up to 1000, compute total(M) = f[M]^N mod MOD, and then compute g[N][M]? But note N varies per test case up to 1000, so we can't precompute g for all N and M because N up to 1000, M up to 1000, that's 1e6 combinations, but there can be up to 100 test cases, and we might compute per test case using DP over M with given N. Since T up to 100, 100 * 1000 = 100k, which is fine. But we need to compute powers f[M]^N for each M and given N, which can be done with fast exponentiation per M (1000 per test case) -> 100k exponentiations (log N) ~ 10 each, total 1e6 ops, fine. However, the recurrence for g(N,M) requires g(N,k) for k<M, and total(N, M-k) for k<M. So we can compute g(N,1..M) in increasing M. For each N, we compute f array, compute total(N,m) = pow(f[m], N, MOD) for m=1..M_max? Since M may vary per test case, we can precompute up to max M among test cases. And for each N, we compute g(N,m) for m up to max M. But N also varies. So we may need to compute for each distinct N separately. However, T up to 100, and max N, M up to 1000. The worst case if all N are different, we could compute DP for each N separately, that would be O(T * M) exponentiations plus O(M^2) for DP? Actually the recurrence for g(N,M) involves sum over k from 1 to M-1 of g(N,k)total(N,M-k). That's O(M) per M, so O(M^2) per N. If M=1000, M^2=1e6 per N. With T=100, that's 100e6 = 1e8, which might be borderline but possibly okay in Python with optimization and mod operations. But we can do better: We can precompute f[0..1000] and maybe precompute powers? But N changes, so we can't precompute total(N,M) for all N up to 1000 because N up to 1000, that would be 1e6 entries, which is okay. Actually we can precompute f[m] for m up to 1000. Then for each N we need total(N,m)=f[m]^N mod MOD. We could precompute all powers f[m]^N for N=1..1000 and m=1..1000? That would be 1e6 values, each computed via exponentiation or by incremental multiplication? Since both dimensions up to 1000, we can precompute a table pow_f[N][M] but that's 10001000=1e6, which is fine memory-wise (~8 MB if integers). But we can also compute on the fly per test case. But if we have up to 100 test cases, and each case might have different N, the DP per case O(M^2) might be okay because 1000^2 = 1e6, times 100 = 100 million operations, each a few modular multiplies, maybe borderline but possibly pass in Python if optimized (using list and loops). However we could also use a more efficient approach: The recurrence g(N,M) = total(N,M) - Σ_{k=1}^{M-1} g(N,k) * total(N, M-k). That is convolution-like. But for each N we can compute g sequentially. Since M up to 1000, O(M^2) is fine.
But wait, there's also the need to compute total(N,M-k). We can precompute an array T[M] = f[M]^N for given N. So for each N, we compute T[0..maxM] (with T[0] maybe 1? For total of width 0? Not needed but can define for completeness). Then we compute g[1..maxM] with g[1]=T[1] (since width 1 is solid). For m from 2 to maxM:
sum_bad = 0
for k in range(1, m):
sum_bad = (sum_bad + g[k] * T[m - k]) % MOD
g[m] = (T[m] - sum_bad) % MOD
Make sure to handle negative modulo.
This works because the recurrence derived seems correct.
Now we need to confirm the recurrence is valid for all M. We derived from smallest crack decomposition. Let's double-check the reasoning: For a wall of width M that is not solid, there exists at least one k in {1,...,M-1} such that all rows have a boundary at k. Let k be the smallest such. Then the left part (width k) has no full crack (by minimality), so it's solid. The right part (width M-k) can be any wall (with any cracks). This decomposition is unique: given a non-solid wall, there is a unique smallest k. Conversely, for any solid left wall of width k and any (possibly non-solid) right wall of width M-k, concatenating yields a wall that has a full crack at k (since every row has boundary at the join) and no full crack at any j<k because left is solid. Thus it's a bijection between non-solid walls and pairs (k, solid left, any right) with 1≤k<M. Therefore, total(N,M) = solid(N,M) + Σ_{k=1}^{M-1} solid(N,k) * total(N, M-k). So solid(N,M) = total(N,M) - Σ_{k=1}^{M-1} solid(N,k) * total(N, M-k). Yes.
We need to be careful about width 0? Not needed.
Now we should verify base case: solid(N,0)? Not used.
Thus algorithm:
Precompute f[0..MAX] where MAX = maximum M over all test cases. f[0]=1 (empty row), f[1]=1, f[2]=2, f[3]=4, f[4]=8, and for i>4: f[i] = f[i-1]+f[i-2]+f[i-3]+f[i-4] mod MOD? Actually MOD is 1e9+7, but f for row tilings can be large but we only need f[i] modulo MOD because we will exponentiate modulo MOD. However, careful: total(N,M) = f(M)^N mod MOD. Since we take modulo after exponentiation, it's okay that f(M) is computed modulo MOD. But is it valid? f(M) may be huge, but we only work modulo MOD. Since exponentiation modulo MOD requires base modulo MOD, it's fine to compute f(M) mod MOD first. However, we need to ensure that the recurrence solid uses total(N,M) modulo MOD, and the combinatorial reasoning holds modulo MOD (since we're counting ways mod MOD). Yes.
Now, we need to handle multiple test cases. We can read all test cases, find maxN and maxM? Actually N and M both up to 1000. The recurrence for solid depends on N because total(N,M) = f(M)^N. So for each distinct N, we need to recompute the T array (powers) and then compute solid values up to max M needed for that N. But note that many test cases may share the same N. So we can process per unique N: For each N, compute solid for all M up to maxM (the maximum M among test cases with that N). Then answer queries accordingly. Since T <= 100, number of distinct N <= 100. But worst-case all N different, up to 100 distinct N. For each N, we would do O(maxM^2) ~ 1e6 operations. 100 * 1e6 = 1e8 operations. Might be okay in Python with some optimizations but could be near time limit? We should try to optimize. Perhaps we can precompute f and also precompute all powers of f[m] for all N up to 1000? That would be a 2D array pow_f[N][m] of size (1001 x 1001) = ~1e6. Compute each using fast exponentiation? That would be 1e6 * logN = ~10 million operations, which is fine. Then for each N, we can retrieve T[m] quickly. Then we need to compute solid(N,M) for all M up to maxM. However, we might compute solid for all N and M up to 1000? That would be 1000 * 1000 = 1e6 entries, and we could compute using DP for each N. That would be 1000 * (1000^2) = 1e9 if done naively (since for each N, O(M^2)). But we can compute solid(N,M) using the recurrence which is O(M) per M, total O(M^2) per N. If we have 1000 N values, that's 1e9. But we only have up to 100 distinct N in test cases, not necessarily 1000. However, we could also compute solid for all N,M by a different approach? Perhaps we can use generating functions? But given constraints, it's likely acceptable to compute per test case O(M^2) since M=1000 and T=100 gives 100e6, which is okay if coded efficiently in PyPy. Many solutions for similar problems do exactly that: precompute f, then for each test case compute g via DP with O(M^2). But note that N can be up to 1000, so total(N,M)=f[M]^N mod MOD, and we need that for each M in DP. Computing f[M]^N for each M via fast exponentiation per M in each test case would be O(M log N) ~ 1000*10=10k per test case, negligible. Then DP O(M^2)=1e6 per test case, total 100e6 = 0.1 billion, might be okay if inner loop is simple.
But we can also compute DP more efficiently by precomputing convolution? Not necessary.
However, I recall that for the LEGO Blocks problem on HackerRank, constraints are N,M up to 1000 and T up to 100, and typical solutions use O(M^2) per test case after precomputing f and powers. So it's fine.
Let's verify with more test cases.
Edge Cases: M=1: output always 1, regardless of N, because only one column, no vertical line. Check recurrence: g[1]=f[1]^N=1^N=1.
M=2: g = f[2]^N - g[1]*f[1]^N = 2^N - 1, matches.
Now we need to ensure that the modulo operation yields positive numbers.
Implementation steps:
- Read T.
- Collect all test cases (N, M). Determine max_M = max of M across test cases.
- Precompute f[0..max_M] using recurrence f[0]=1, f[1]=1, f[2]=2, f[3]=4, f[4]=8, for i from 5 to max_M: f[i] = (f[i-1] + f[i-2] + f[i-3] + f[i-4]) % MOD.
Actually we can compute from 1 upwards: for i in range(1, max_M+1): if i==1: f[i]=1; else if i==2:2; etc. Better: f[0]=1; for i in range(1,max_M+1): f[i] = 0; then for i from 1 to max_M: for step in 1..4: if i-step >=0: f[i] += f[i-step] mod. That's typical DP.
- For each test case, we need to compute g(N,M). We could compute per test case:
- Precompute array T of length M+1 (maybe up to max_M) where T[w] = pow(f[w], N, MOD) for w=0..max_M? But we only need up to M. But DP needs T for all values up to M. So compute T[0]? We might need T[0] for total(N,0)? In the recurrence, we sum over k from 1 to M-1 and use total(N, M-k). For M-k could be 0? When k=M, we don't use. So M-k >=1 because k<M. So we don't need total for width 0. So we can ignore T[0]. But we may use T[1]..T[M].
- Then compute g array of size M+1 (index from 0 maybe). Initialize g[1] = T[1] (since f[1]=1, T[1]=1). Actually g[1] = T[1] (1^N=1). Or we can compute from m=1 to M:
if m==1: g[1]=T[1]
else:
sum_bad = 0
for k in range(1, m):
sum_bad = (sum_bad + g[k] * T[m - k]) % MOD
g[m] = (T[m] - sum_bad) % MOD
- Ensure g[m] is non-negative: g[m] = (T[m] - sum_bad) % MOD (Python's % yields positive).
- Output g[M].
This per test case DP is O(M^2). For M=1000, that's ~500k iterations (since sum of 1..999 ~ 500k) per test case. Actually 999+998+...+1 = about 500k. So per test case ~500k operations, times T=100 => 50 million. That's fine. Plus exponentiation for each M (maybe up to 1000) per test case: 1000 * logN (max 10) ~10k operations, total ~10k*100=1e6, negligible. So total about 50 million modular multiplications and additions, should run within a few seconds in PyPy.
But we must be careful: The DP inner loop uses multiplication and addition mod. Python's ints are big but mod keeps them within range. It's okay.
We could also precompute for all N and M once to answer queries quickly, but per test case is okay.
However, note that if multiple test cases have same N, we would recompute the DP from scratch each time, which is wasteful. But we can memoize per N: Use dictionary: computed_N = set of N for which we have computed g up to max_M_needed for that N. For each N, compute g_N array up to max_M_all (or up to the maximum M among test cases with that N). Then answer all queries with that N by looking up g_N[M]. That reduces total work to at most number of distinct N * (max_M^2). Since distinct N <= T (100). In worst case, if all N are distinct, it's the same as per test case: 100 * 500k = 50 million. But if many test cases share same N, we save time. So we can implement caching.
Implementation plan:
- Read all test cases into list cases = [(N, M)].
- Determine global max_M = max M across cases.
- Precompute f up to max_M.
- Group cases by N: For each distinct N, find max M needed for that N (max_M_N). Then compute g array for that N up to that max_M_N using DP as described (but we need T up to that max_M, computed using f and pow). Then store g_N array (size max_M_N+1, index by width). Then for each case with that N, answer = g_N[M].
- Since N may be up to 1000, but distinct N at most 100, it's fine.
Now we must ensure correctness for all M. Let's test some random small values manually.
Consider N=1 (height 1). Then solid wall must have no vertical crack that goes through the only row. But a vertical crack through the wall exists if there is a column where the row has a boundary. For a single row, a crack exists at column k iff the row has a boundary at k. The wall is solid if there is no such k? Actually the condition: "cannot make a vertical cut from top to bottom without cutting one or more lego blocks." For a single row, a vertical cut will cut a block unless the cut aligns exactly with a gap between blocks. So if the row has any gaps (boundaries) at some k, then cutting at that k would not cut any block? Wait: The cut is a vertical line; if it passes through a gap between blocks, does it cut any block? If the gap is of zero width (just the line between bricks), the line would not intersect any brick because bricks are separated by a theoretical line. So yes, at a gap, the line would not cut any brick. So for a single row, the wall is solid if there are no gaps, i.e., the row consists of a single brick of length M. But also if there are multiple bricks but the gaps are not aligned across rows (but only one row), then any gap creates a vertical line that doesn't cut any brick across that single row; and since there is only one row, that line would not cut any brick at all, making the wall not solid. So for N=1, a wall is solid only if the row is a single brick covering the entire width M (no internal boundaries). So g(1,M) should equal the number of tilings of width M that have no internal boundaries, i.e., only one brick of length M, provided that M is one of the allowed lengths? But we have bricks of lengths 1,2,3,4. So if M is between 1 and 4, there is exactly 1 way: use a single brick of length M. If M>4, can we use a single brick? No, because max brick length is 4. So there is no way to tile a row of width >4 without internal boundaries. Therefore, g(1,M) should be 1 if M in {1,2,3,4}, else 0. Let's test our recurrence with N=1.
Compute f(M) as number of tilings. Then total(1,M) = f(M). Compute g(1,M) using recurrence.
For M=1: g= total=1. Good.
M=2: total = f(2)=2. g(1,2) = total - g(1,1)total(1,1) = 2 - 11 = 1. That matches (single brick of length 2).
M=3: total=4. g(1,3)= total - [g1,1total2 + g1,2total1] = 4 - (12 + 11) = 4-3=1. Yes (single brick of length 3).
M=4: total=8. g(1,4)=8 - [g1,1total3 + g1,2total2 + g1,3total1] =8 - (14 + 12 + 11)=8-7=1. Good.
M=5: total = f(5). Compute f(5) = f4+f3+f2+f1 =8+4+2+1=15? Wait f(5)= f4+f3+f2+f1 =8+4+2+1=15. Let's compute using recurrence: f5=15. Then g(1,5) = total - sum_{k=1..4} g(1,k)*total(1,5-k). Compute:
g1,1=1; total4=8? Actually total(1,4)=f4=8.
k=1: 1*8=8.
k=2: g1,2=1; total(1,3)=4 => 4.
k=3: g1,3=1; total(1,2)=2 =>2.
k=4: g1,4=1; total(1,1)=1 =>1.
Sum = 8+4+2+1=15.
Then g = 15-15=0. So indeed no solid wall for M=5 when N=1. So recurrence yields correct.
Now test N=2, M=5: Should produce something. We'll compute later maybe. But seems fine.
Now we need to consider mod = 1000000007.
Thus algorithm is correct.
But wait: The problem statement says: "The blocks can only be placed horizontally." That means they are lying flat, with their length along the width. That's what we assumed. Also height N is number of layers (each block height 1). Yes.
Now, one more nuance: The blocks are of sizes (1 x 1 x 1), (1 x 1 x 2), (1 x 1 x 3), (1 x 1 x 4). The width is the third dimension? Actually typical notation: length x width x height? But they said "sizes (1 x 1 x 1), (1 x 1 x 2), (1 x 1 x 3), and (1 x 1 x 4)." Then they say "wall of height N and width M." They also say "blocks can only be placed horizontally." So likely the first two dimensions are depth and height? But they said "1 x 1 x L", maybe it's depth x height x width? It doesn't matter; we just treat bricks as covering 1 unit in height (vertical) and L units in width, depth is 1 (ignored). So our interpretation stands.
Now, we should also consider if the wall is considered as a 3D structure? But since depth is 1, it's essentially 2D. So correct.
Now we will implement.
Implementation details:
- MOD = 1000000007
- Precompute f up to MAXM (max M across all test cases). Use list of size MAXM+1, f[0]=1. Then for i in range(1, MAXM+1): f[i] = 0; for j in 1..4: if i>=j: f[i] = (f[i] + f[i-j]) % MOD.
- For each distinct N:
- Determine needed M_max for that N (max M among test cases with that N).
- Compute array T of length needed_M_max+1: T[0] = 1? Not needed but maybe we set T[0]=1 for convenience. Actually for total(N,0) if we need? But not used. We'll set T[0]=1 (empty row? A wall of width 0 would be degenerate; but we won't use it because k< m so m-k >=1). However, in DP when we compute g[m] we use T[m - k] where m-k can be any from 1 to m-1. So we don't need T[0]. But we can set T[0] = 1 (since there's exactly one way to tile width 0? f(0)=1; then total(N,0)=1^N=1). But if we inadvertently use it, it's fine. But we won't use it because k ranges from 1 to m-1, so m-k ranges from m-1 down to 1. So no zero. So we don't need T[0].
- Compute T[w] = pow(f[w], N, MOD) for w=1..needed_M_max.
- Then compute g[1] = T[1] (since f[1]=1, T[1]=1). Actually f[1]=1, so T[1]=1^N=1.
- For m from 2 to needed_M_max:
sum_bad = 0
for k in range(1, m):
sum_bad = (sum_bad + g[k] * T[m - k]) % MOD
g[m] = (T[m] - sum_bad) % MOD
- Store g array for this N (maybe a dict: cache[N] = g). But careful: g array length may be only up to needed_M_max. For queries with smaller M, we just index. For safety, we could compute up to global max_M to reuse across N? Not needed.
- For each test case (N,M), retrieve g from cache[N][M] and print.
Now check sample:
Input:
4
2 2
3 2
2 3
4 4
We'll compute f[1]=1, f[2]=2, f[3]=4, f[4]=8.
For N=2: compute T[1]=1, T[2]=2^2=4, T[3]=4^2=16, T[4]=8^2=64.
g[1]=1.
m=2: sum = g1T1 =11=1; g2=4-1=3.
m=3: sum = g1T2 + g2T1 =14 + 31 =7; g3=16-7=9.
m=4: sum = g1T3 + g2T2 + g3T1 =116 + 34 + 91 =16+12+9=37; g4=64-37=27? Wait 64-37=27, but sample says 3375 for N=4, M=4. That's for N=4, not N=2. For N=2, M=4, our g4=27? Let's compute manually: total(2,4)=8^2=64. Subtract sum of g(2,k)*total(2,4-k):
g(2,1)=1, total(2,3)=4^2=16 =>16
g(2,2)=3, total(2,2)=2^2=4 =>12
g(2,3)=9, total(2,1)=1 =>9
Sum=37, 64-37=27. So g(2,4)=27. This seems plausible. For N=4: we computed earlier g(4,4)=3375. So our DP yields that.
Now note: The DP algorithm uses T[m] = f[m]^N. For N=4, f[4]=8, 8^4=4096, sum from earlier: 34^4? Actually we derived formula g(N,4) = 8^N - 34^N + 32^N - 1. For N=4: 8^4=4096, 4^4=256, 3256=768, 2^4=16, 3*16=48, so 4096 - 768 + 48 -1 = 3375. Good.
Thus algorithm works.
Now we must consider potential pitfalls: The recursion for f[0] should be defined as 1. But ensure that f[0] is not used incorrectly. Since we compute f[1..maxM] using recurrence with f[0] included. Eg f[1] = f[0] =1. That's fine.
Now check the DP for g: When m=2, we compute sum over k=1: g[1]T[1] =1T[1]. T[1] = f[1]^N =1^N =1. So sum=1. g[2]=T[2]-1 = f[2]^N -1. f[2]=2, so 2^N -1.
Now, does g[1] correctly represent solid walls of width 1? Yes, because there are no internal columns, so any tiling of width 1 is just a single 1-length brick (only one way). But f(1)=1, so total=1, solid=1.
Now, verify for N=1, M=2, we got 1, which is correct.
Now, let's test for N=1, M=3, we got 1, correct.
Now, think about M up to 1000, f[M] can be computed modulo MOD. But careful: When we compute T[w] = pow(f[w], N, MOD), we need f[w] mod MOD. However, note that f[w] might be 0 mod MOD? Possibly if MOD divides f[w]? But MOD is prime > 1e9, and f[w] values are numbers that grow exponentially but less than MOD for w up to 1000? Let's estimate: f[w] grows like ~ c * α^w where α ≈ 1.92756 (the real root of x^4 = x^3+x^2+x+1? Actually it's the Pisot number for tribonacci? Wait it's tetranacci: f(n) = f(n-1)+f(n-2)+f(n-3)+f(n-4). The growth factor is about 1.92756^w. 1.92756^1000 is astronomically huge, far exceeding MOD. So f[w] mod MOD will be some number between 0 and MOD-1. It could be 0 if MOD divides f[w]. Is that possible? Possibly but very unlikely? But even if f[w] ≡ 0 mod MOD, then T[w]=0^N = 0 for N>0. That's fine. So no issue.
Now, the recurrence for g uses modular arithmetic, so it's fine.
One more nuance: The recursion we derived assumes that the smallest crack k is strictly less than M, and the left part is solid. But what about the possibility of multiple cracks at the same smallest? Actually the smallest crack is unique by definition (the minimum column index with a crack). So it's fine.
Now, we must confirm that the recurrence correctly counts walls where there is a crack but also the left part being solid includes the possibility that left part width k has a crack? No, because left solid means no crack, so left part cannot have any full crack. That's enforced.
Now, check for M=2, N=1: total=2, g=1, and the non-solid walls are those with a crack at column 1? Actually the only non-solid wall is the one with two 1x1 blocks, which has a crack at column 1. That wall's smallest crack is 1. Left part width 1 is solid (only one block). Right part width 1 is solid as well. So our decomposition says non-solid count = g(1,1)total(1,1) =11=1. Correct.
Now, for M=3, N=1: total=4. Solid walls: only the single brick of length 3 (1 way). Non-solid: three others. Let's see smallest cracks: For tiling 1+1+1, smallest crack is at 1? Actually boundaries at 1 and 2. Smallest k=1. Left part width1 solid, right part width2 any (total(1,2)=2). That yields 12=2 configurations? But there is also tiling 2+1: boundaries at 2. Smallest k=2? Left part width2? For 2+1, there is a boundary at 2, no boundary at 1. So smallest crack is 2. Left part width2 must be solid? Is a row of width2 consisting of a single 2-block solid? Yes, because no internal boundary. So left solid: width2, solid count g(1,2)=1. Right part width1 total=1. That gives 11=1. Similarly tiling 1+2: boundaries at 1, so smallest crack=1? Actually 1+2 has a boundary at 1, but not at 2. So smallest crack=1. Left part width1 solid, right part width2 any (total=2) yields 1*2=2. But we already counted 2 from 1+1+1? Wait 1+1+1 also smallest crack=1, left width1 solid, right width2 any: there are two possibilities for right part? For left width1, the right width2 can be tiled in 2 ways: either as one 2-block or as two 1's. So that yields 2 configurations: indeed, those correspond to the two configurations where leftmost brick is 1 and the remaining width2 is either [2] or [1,1]. That yields rows: [1,2] and [1,1,1]. So that accounts for both 1+2 and 1+1+1. But 1+2 is accounted as left 1, right 2 (using a 2-block). That's one of them. And 1+1+1 is left 1, right two 1's. So both are counted under k=1. Then the tiling 2+1 is counted under k=2. So total non-solid count = 2+1=3, matches. So decomposition works.
Now, what about walls where there is a crack at multiple columns, but the smallest is k. That is captured.
Thus recurrence is solid (pun intended).
Now we must ensure we don't double-count when we compute g for each N.
Now, about time: For each distinct N, we compute T array up to needed M. We can compute T[w] using pow. Python's pow(base, exp, mod) is efficient.
Then DP: for m from 2 to maxM: sum over k=1..m-1 of g[k]*T[m-k]. That's O(maxM^2/2). For maxM=1000, it's 500k iterations per distinct N. With at most 100 distinct N, that's 50 million iterations. Each iteration does a multiplication and addition modulo. That's fine in PyPy. But we might also need to handle mod operations carefully. Use local variables for MOD, and maybe pre-allocate lists.
To further optimize, we could compute g for all N and M via DP that uses precomputed total for all N? But that's not necessary.
I'll implement with caching.
Implementation steps in code:
import sys
MOD = 1000000007
def precompute_f(maxM):
f = [0]*(maxM+1)
f[0] = 1
for i in range(1, maxM+1):
total = 0
for j in range(1,5):
if i-j >= 0:
total = (total + f[i-j]) % MOD
f[i] = total
return f
But we can also compute f more efficiently by incremental sliding window: Since f[i] = f[i-1]+f[i-2]+f[i-3]+f[i-4], we can compute iteratively.
f = [0]*(maxM+1)
f[0]=1
if maxM>=1: f[1]=1
if maxM>=2: f[2]=2
if maxM>=3: f[3]=4
if maxM>=4: f[4]=8
for i in range(5, maxM+1):
f[i] = (f[i-1] + f[i-2] + f[i-3] + f[i-4]) % MOD
But careful: Actually f[4] from recurrence: f[4]=f[3]+f[2]+f[1]+f[0]=4+2+1+1=8. So yes. But for i=5, we need f[4]..f[1] all computed. So that works.
Now, for each distinct N, compute g up to maxM_for_N.
We'll store cache as dictionary: cache = {} where key = N, value = list g (index by width). We'll compute up to needed M (max_M_for_N). But if later another test case with same N but larger M appears, we might need to extend the cached g array. To handle that, we could when grouping, for each N we compute up to the maximum M among cases with that N. So we can group first.
Implementation:
-
Read all lines.
-
Parse T.
-
cases = []
-
maxM_global = 0
-
for _ in range(T):
N,M = map(int, input().split())
cases.append((N,M))
maxM_global = max(maxM_global, M)
-
Precompute f up to maxM_global.
-
Group cases by N: use dict groups: keys N, values list of M. Also for each N compute max_M = max of those M.
-
For each N in groups:
maxM_N = groups[N]['max'] or compute.
compute T array from 1 to maxM_N
T = [0]*(maxM_N+1)
for w in range(1, maxM_N+1):
T[w] = pow(f[w], N, MOD)
compute g
g = [0]*(maxM_N+1)
g[1] = T[1] # which is 1
for m in range(2, maxM_N+1):
s = 0
# for k in range(1, m):
# s = (s + g[k] * T[m-k]) % MOD
# We can loop
for k in range(1, m):
s = (s + g[k] * T[m-k]) % MOD
g[m] = (T[m] - s) % MOD
cache[N] = g
-
Then for each case (N,M): print(cache[N][M])
But careful: What about N=0? Not allowed (N≥1). So fine.
Now, test with sample.
Let's code quickly.
But wait: For N=1, g[1] = T[1] = 1. Then for m=2: sum = g[1]T[1] = 11=1, g[2]=T[2]-1=2-1=1? But T[2]=f[2]^1 =2, so g[2]=1 correct. For m=3: sum = g1T2 + g2T1 = 12 + 11 =3, T[3]=4, g[3]=1. Good.
Now, note that g[1] is T[1] = 1 always, as f[1]=1.
Now, we must consider that f[0] is defined, but we don't use.
Now, we must also ensure that the DP works when maxM_N = 1. Then loop from 2 to 1 doesn't run, and we only have g[1] defined.
Now, are there any pitfalls about the initial value g[0]? Not needed.
Now, performance: For each distinct N, we do DP O(maxM_N^2). Since sum over distinct N of maxM_N^2 could be up to 100 * 1e6 = 1e8 if all maxM_N=1000, but in practice maxM_N is the maximum M for that N, which could be 1000 for each distinct N. However, if we have many distinct N, each with max M=1000, that's 100 * 1e6 = 100 million iterations. Each iteration includes a multiplication and addition mod, plus loop overhead. Might be near the limit but likely okay in PyPy (especially if we use PyPy's JIT). But we can further optimize by using that T is known and we are doing a convolution-like sum. But we can also compute g using a recurrence that uses cumulative sums? However, not necessary.
Alternatively, we could precompute g for all N and M up to 1000 using a more efficient method: For each M, we could compute something like generating functions, but that may be complex.
We can also note that the DP for g for each N is independent, but we might compute all N simultaneously? Since N varies, T depends on N, so not easy.
But 100 distinct N with M=1000 gives about 50 million iterations (since sum_{m=2}^{1000} (m-1) = 1000999/2 ≈ 500k per N, not 1e6. Wait careful: The number of inner loop operations is sum_{m=2}^{M} (m-1) = M(M-1)/2 ≈ 500k for M=1000. So per N: 500k operations. For 100 N: 50 million. That's the figure. Each operation: multiplication (g[k] * T[m-k]) and addition mod. That's fine.
Now, also for each N we compute T array of 1000 pow operations: 1000 * log N (max 10) = 10k, so 1 million pow operations across 100 N, negligible.
Thus overall should be fine.
Now, we need to be careful about reading input fast: use sys.stdin.read or sys.stdin.buffer.
We'll implement.
One more subtlety: The recurrence we used: g(N,M) = total(N,M) - sum_{k=1}^{M-1} g(N,k) * total(N, M-k). But is this correct when there is a crack at position k and also other cracks? The smallest crack approach ensures each non-solid wall is counted exactly once. This recurrence is standard for "connected" compositions (like number of compositions where you can't split). Indeed, it's similar to number of ways to tile a rectangle such that there is no vertical line of weakness. This is analogous to "number of ways to partition a set where blocks are not separable", akin to "non-splittable" compositions. So it's correct.
We should test a few more cases manually to be sure.
Case: N=2, M=5. Compute using our method:
f[1]=1, f2=2, f3=4, f4=8, f5=15? Actually f5 = 8+4+2+1=15. f6 = f5+f4+f3+f2 =15+8+4+2=29? Wait 15+8=23, +4=27, +2=29. f7 = 29+15+8+4=56? 29+15=44, +8=52, +4=56. But we only need up to 5.
N=2:
total2[1]=1
total2[2]=2^2=4
total2[3]=4^2=16
total2[4]=8^2=64
total2[5]=15^2=225
Now compute g[1]=1
g[2]=4-1=3
g[3]=16 - (g1total2[2] + g2total2[1]) =16 - (14 + 31)=16-7=9
g[4]=64 - (g1total2[3] + g2total2[2] + g3total2[1]) =64 - (116 + 34 + 91) =64 - (16+12+9)=64-37=27
g[5]=225 - (g1total2[4] + g2total2[3] + g3total2[2] + g4total2[1]) =225 - (164 + 316 + 94 + 271) =225 - (64+48+36+27) =225 - 175 = 50.
So g(2,5)=50. Let's try to reason if plausible. total=225, solid=50. I could try to compute via inclusion-exclusion directly for small N,M but not needed. Likely correct.
Now check another: N=3, M=3. Using formula: g(3,3)=4^3 - 2^{4} +1 = 64 -16 +1=49. Our recurrence: f[3]=4, total=64. g[2]=2^3-1=8-1=7. g[1]=1. Then g[3]=64 - (18 + 71) =64-15=49. Good.
Now, we should ensure the modulo operation yields positive numbers when subtracting. Use (T[m] - s) % MOD.
Now, we need to handle the case where N is large but M is small. Works.
Now, confirm constraints: T up to 100, N, M up to 1000. So max M = 1000, good.
Now, potential bug: When computing f[i] for i up to 1000, the numbers may exceed Python's int but modulo keeps them small.
Now, we need to group test cases by N. However, it's possible that two test cases with same N have different M, and we compute g only up to the max M needed for that N. But what if later we process another test case with same N but larger M not initially grouped? We'll group all before processing, so we know all M for each N. So fine.
Now, implement.
But note: The DP uses T array of length maxM_N+1. Since we need T[m-k] for m up to maxM_N, we need T up to maxM_N. That's fine.
Now, edge: M=0? Not allowed.
Now, confirm that f[0]=1. In DP we never use T[0] because m-k >=1 for k<m.
Now, implement.
Now, think about possible integer overflow: Python unlimited.
Now, test sample.
We'll code and test.
But before finalizing, let's think about alternative interpretations: Could the vertical cut be considered at any x coordinate, not just integer boundaries? As argued, if cut is not at integer, it will cut through bricks unless there is a gap of zero width? Actually if the bricks are placed side by side, there is no gap; the boundary is a line. A cut at a non-integer coordinate will intersect either a brick or the boundary? For a continuous model: Suppose we have intervals covering [0,M] with lengths that are integers, placed consecutively without gaps. The boundaries between bricks are at integer positions. For a vertical line at x = c, where c is not an integer, it lies strictly inside some unit interval. Since bricks are of integer lengths, the union of intervals covers the whole [0,M] without gaps (because the bricks exactly cover the width with no gaps). Actually, the row exactly covers the width M; there are no gaps; the boundaries are just points. So any line at a non-integer x will intersect the interior of some brick because the brick's coverage is a continuous interval. For example, if a brick covers [0,2] (length 2), then line at x=1.5 will intersect that brick. So only lines exactly at integer positions could possibly go through no brick if the integer position is exactly at a boundary between bricks. If the row has no boundary at that integer (i.e., a brick spans across), then the line at that integer would be inside a brick (since the brick covers up to that point? Actually if a brick covers [0,2], the point x=2 is the right endpoint. If you cut exactly at x=2, the line would be at the edge of the brick. Does that count as cutting the brick? The problem statement says "without cutting any lego block". If the cut is exactly at the boundary, does it cut any block? Typically, if you cut exactly along the seam, you don't cut any block. So lines at integer positions that align with a brick boundary are gaps; lines at integer positions that are in the middle of a brick (i.e., at an endpoint of a brick? Actually bricks have endpoints at integer positions. If a brick spans from 0 to 2, its endpoints are at 0 and 2. At x=2, it's an endpoint, which is the boundary between that brick and the next. If there is no next brick because it's the end, then the wall ends at M. But internal positions: if a brick spans from 0 to 2, then at x=1, it's interior; at x=2, it's endpoint. At x=2, there might be a boundary if the next brick starts at 2. But if the brick ends at 2 and another starts at 2, the line at x=2 is the shared boundary. If the brick ends at 2 and that's the end of the wall (M=2), then the line at x=2 is the wall edge; probably not considered as cut through the wall because it's the boundary of the wall. The problem likely considers vertical cuts inside the wall, not at the edges. So we only consider k from 1 to M-1. So correct.
Thus solution stands.
Now, final answer: code as described.
But wait, there is a nuance: The blocks can only be placed horizontally. Does that mean we cannot rotate them? They are already horizontal. Yes.
Now, I recall a known HackerRank problem "LEGO Blocks" where the solution is exactly as described: compute ways to build a single row (f), then total = f^N mod MOD, then solid = total - sum_{i=1}^{M-1} solid[i] * f[M-i]^N. That's what we have.
However, I also recall that in some versions, they also consider the possibility that blocks can be placed in any orientation? But here they say only horizontally.
Thus finalize.
Let's also consider if there is any possibility of stacking blocks vertically? They said "blocks can only be placed horizontally", meaning each block lies flat, not standing upright. So each row is composed of blocks placed side by side, each of height 1. So stacking multiple rows on top of each other gives height N. So correct.
Now, test with additional random.
N=1, M=6: total = f6? Let's compute f6: f6 = f5+f4+f3+f2 =15+8+4+2=29. Then g6 =? using recurrence should give 0 because width >4 cannot be tiled by a single block. Let's compute quickly: g1=1, g2=1, g3=1, g4=1, g5=0. For M=6: total=29. Sum over k=1..5: g1total5 + g2total4 + g3total3 + g4total2 + g5total1 = 1 f5^1? Actually total5 = f5 =15, total4=8, total3=4, total2=2, total1=1. So sum = 15+8+4+2+0 = 29, so g6=0. Good.
Now, confirm that g5 computed earlier for N=1: we had g5=0. Good.
Now, what about N=2, M=6? Let's compute maybe to see if any inconsistency, but not needed.
Now, we should be careful about using zero-based indexing.
Implementation details:
We'll parse input using sys.stdin.read().split() to get all integers quickly.
Pseudo:
import sys
MOD = 1000000007
def main():
data = sys.stdin.read().strip().split()
if not data: return
it = iter(data)
T = int(next(it))
cases = []
maxM = 0
for _ in range(T):
N = int(next(it)); M = int(next(it))
cases.append((N,M))
if M > maxM: maxM = M
# precompute f up to maxM
f = [0]*(maxM+1)
f[0] = 1
if maxM >= 1:
f[1] = 1
if maxM >= 2:
f[2] = 2
if maxM >= 3:
f[3] = 4
if maxM >= 4:
f[4] = 8
for i in range(5, maxM+1):
f[i] = (f[i-1] + f[i-2] + f[i-3] + f[i-4]) % MOD
# group cases by N
from collections import defaultdict
groups = defaultdict(list)
for N, M in cases:
groups[N].append(M)
# cache for each N: g list up to maxM_for_N
cache = {}
for N, Mlist in groups.items():
maxM_N = max(Mlist)
# compute T up to maxM_N
T_arr = [0]*(maxM_N+1)
# T_arr[0] = 1 # not needed but can set
for w in range(1, maxM_N+1):
T_arr[w] = pow(f[w], N, MOD)
# compute g
g = [0]*(maxM_N+1)
if maxM_N >= 1:
g[1] = T_arr[1] # 1
for m in range(2, maxM_N+1):
s = 0
# loop over k from 1 to m-1
# could use local variables for speed
for k in range(1, m):
s = (s + g[k] * T_arr[m - k]) % MOD
g[m] = (T_arr[m] - s) % MOD
cache[N] = g
out_lines = []
for N, M in cases:
out_lines.append(str(cache[N][M]))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
That should work.
Now, test with sample.
We'll run mental: should output 3,7,9,3375.
Now, need to ensure that for N where maxM_N may be 1, we have g[1] set. In code we set if maxM_N >=1: g[1]=T_arr[1]. That's fine.
Now, what about N where maxM_N is 0? Not possible because M>=1.
Now, potential bug: For N, we compute T_arr[w] = pow(f[w], N, MOD). For w=1, f[1]=1, so T_arr[1]=1. g[1]=1.
Now, need to consider that f[0] is defined but not used. However, when we compute f[1] via recurrence from 0, we used f[0]=1, which is consistent.
Now, the only other nuance: The recurrence for g might be derived under assumption that the wall is built by stacking rows; but what about the vertical alignment? The condition about "solid structure" also says "It should not be possible to separate the wall along any vertical line without cutting any lego block". That is exactly our condition.
Now, confirm that the recurrence for g works when N is large but M small.
Now, possible overflow in multiplication: g[k] * T_arr[m-k] might be up to MOD^2, but Python handles big ints and we mod after addition.
Now, could we precompute f up to 1000 once, then for each N compute g? Yes.
Now, final check: The sample input and output should match.
Now, consider if any test case has M=0? Not per constraints.
Now, we must ensure that the grouping approach works when there are many test cases; we used defaultdict.
Now, think about time for building f: O(maxM) trivial.
Now, let's test with some random values using manual small N,M to verify pattern.
We already tested several.
Now, I'd like to test with N=2, M=6 using our code later.
But overall seems fine.
Now, double-check: In the recurrence, we used T_arr[m-k] = f[m-k]^N. That is total(N, m-k). But in the decomposition, we used total(N, M-k) for the right part. However, note: The right part is of width M-k, and its total number of configurations is f(M-k)^N, yes. But is there any restriction that the right part must be aligned with the left part in terms of rows? No, each row's right part tiling is independent of other rows. So total(N, M-k) = f(M-k)^N. Good.
Now, one more nuance: When we concatenate left solid wall of width k and any right wall of width M-k, does the resulting wall automatically have a full crack at k? Yes, because each row has a boundary at k (since left and right tilings are separate). So it's counted as a non-solid wall. However, what about the case where the left solid wall itself might have a crack at its right edge? No, solid wall by definition has no full crack (i.e., no column where all rows have a boundary). The right edge is column k, which is the boundary between left and right. But that's not a column inside the left part? The left part's columns are 1..k. The crack we consider at position k is between column k and k+1. That is the rightmost boundary of the left part. In the left part considered alone (width k), we are not considering the right edge as a crack because the wall of width k only covers columns 1..k, and there is no column after k. So a crack at the rightmost edge of the left part is not considered in the definition for that subwall because the definition only considers vertical lines within the wall's width? Actually for a wall of width k, vertical lines considered are between columns 1..k-1 (i.e., internal lines). The line at position k is the right boundary of the wall, not an internal line. So the left part being solid means there is no internal column j (1 ≤ j ≤ k-1) where all rows have a boundary. So it's fine that at the join, there is a boundary; that's not considered a crack for the left part alone. So decomposition holds.
Thus recurrence valid.
Now, final code.
But we must also consider that the wall height N can be up to 1000, and we compute f[M]^N mod MOD using pow, which is fine.
Now, I'll produce final answer.
Potential improvements: For DP inner loop, we can use a list comprehension or use precomputed prefix sums? Not needed.
Now, we might worry about recursion depth? Not using recursion.
Now, final code.
One more check: In precomputing f, we set f[0]=1, f[1]=1, f[2]=2, f[3]=4, f[4]=8. But what if maxM is less than 4? We need to handle correctly. Use conditionals or simply compute using the recurrence from i=1..maxM with j from 1..4 if i-j>=0. That's simpler and avoids conditionals. We'll implement that way for robustness.
So:
f = [0]*(maxM+1)
f[0] = 1
for i in range(1, maxM+1):
total = 0
for j in range(1,5):
if i-j >= 0:
total = (total + f[i-j]) % MOD
f[i] = total
This works for all i. For i=1, it adds f[0] only -> 1. i=2: f[1]+f[0]=1+1=2. i=3: f[2]+f[1]+f[0]=2+1+1=4. i=4: f[3]+f[2]+f[1]+f[0]=4+2+1+1=8. Good.
Thus we can use this.
Now, final answer code:
import sys
from collections import defaultdict
MOD = 1000000007
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
T = int(next(it))
cases = []
maxM = 0
for _ in range(T):
N = int(next(it)); M = int(next(it))
cases.append((N, M))
if M > maxM:
maxM = M
# precompute f[m] = number of ways to tile a single row of width m
f = [0] * (maxM + 1)
f[0] = 1
for i in range(1, maxM + 1):
total = 0
for j in range(1, 5):
if i - j >= 0:
total = (total + f[i - j]) % MOD
f[i] = total
# group test cases by N
groups = defaultdict(list)
for N, M in cases:
groups[N].append(M)
cache = {} # N -> list g of length (maxM_for_N+1)
for N, Mlist in groups.items():
maxM_N = max(Mlist)
# T[w] = f[w]^N % MOD
T = [0] * (maxM_N + 1)
for w in range(1, maxM_N + 1):
T[w] = pow(f[w], N, MOD)
g = [0] * (maxM_N + 1)
if maxM_N >= 1:
g[1] = T[1] # = 1^N = 1
for m in range(2, maxM_N + 1):
s = 0
# sum over k=1 to m-1
for k in range(1, m):
s = (s + g[k] * T[m - k]) % MOD
g[m] = (T[m] - s) % MOD
cache[N] = g
out = []
for N, M in cases:
out.append(str(cache[N][M]))
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
Test with sample.
Let's simulate:
Input: 4, then pairs.
maxM=4.
Precompute f: f[0]=1, f[1]=1, f[2]=2, f[3]=4, f[4]=8.
Groups: N=2: Mlist [2,3]; N=3: [2]; N=4: [4]. Actually note: first case (2,2), third (2,3), second (3,2), fourth (4,4). So groups: 2: [2,3]; 3: [2]; 4: [4].
For N=2, maxM_N=3. Compute T[1]=1, T[2]=4, T[3]=16. g[1]=1; g[2]=4 - g1T1=4-1=3; g[3]=16 - (g1T2 + g2T1)=16-(14+3*1)=16-7=9. So cache[2] = [_,1,3,9] (index 0 unused). Then for case (2,2) -> 3, (2,3)->9.
For N=3, maxM_N=2. T[1]=1, T[2]=8? f[2]=2, 2^3=8. g[1]=1; g[2]=8 -1=7. So (3,2) ->7.
For N=4, maxM_N=4. T[1]=1, T[2]=16 (2^4=16), T[3]=256 (4^4=256), T[4]=4096 (8^4=4096). g[1]=1; g[2]=16-1=15? Wait but earlier we derived g(4,2)=2^4 -1 =16-1=15. But sample output for (3,2) is 7, not for N=4. So for N=4, g(4,2)=15; g(4,3) = 4^4 - 2^{5} +1 =256 -32 +1=225; g(4,4)=3375. So (4,4) ->3375. So correct.
Thus output lines: 3,7,9,3375. Sample matches.
Now, finalize.
But wait: In the code, for N=4, when computing T[2] = pow(f[2],4) = 2^4=16, correct; g[2] = T[2] - g[1]T[1] = 16 - 11 =15, correct. Good.
Thus final answer.
But before final, ensure that for N large like 1000, pow with exponent 1000 is fine.
Now, time complexity: Precompute f O(maxM*4)=4000. For each distinct N: T computation O(maxM_N) pow, each O(log N) ~10; and DP O(maxM_N^2). With at most 100 distinct N, maxM_N may be up to 1000, so total DP operations about 50 million. This should run within a second or two in PyPy? Possibly 2-3 seconds. But on HackerRank typical time limit 2 sec? This problem may be from HackerRank "LEGO Blocks" with constraints up to 1000 and T up to 1000? Actually the problem statement says T up to 100, so it's fine.
But I recall the original HackerRank problem had T up to 1000 and N,M up to 1000. With T=1000, 1000 distinct N is possible, then DP 1000 * 500k = 500 million, too high. However, constraints here are T ≤ 100. So okay.
If we wanted to optimize further, we could precompute all g(N,M) for all N and M up to 1000 using a different DP that processes N and M simultaneously? Perhaps using the concept of exponentiation of generating functions, but not needed.
Given the provided constraints, the solution is acceptable.
Now, let's produce final answer.
One more thing: The problem statement in the sample input uses "2 2", "3 2", "2 3", "4 4". Our output matches.
Now, final answer: Provide code and explanation.
We'll output final code as above.
But we must consider if there is any case where f[w] is 0 mod MOD and N>0, then T[w]=0. That's fine.
Now, final answer. ```python
import sys
from collections import defaultdict
MOD = 1_000_000_007
def main() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
t = int(next(it))
cases = []
max_m = 0
for _ in range(t):
n = int(next(it))
m = int(next(it))
cases.append((n, m))
if m > max_m:
max_m = m
# ---------- precompute f[m] : tilings of one row of width m ----------
f = [0] * (max_m + 1)
f[0] = 1
for i in range(1, max_m + 1):
total = 0
for j in range(1, 5):
if i - j >= 0:
total = (total + f[i - j]) % MOD
f[i] = total
# ---------- group test cases by N ----------
groups = defaultdict(list)
for n, m in cases:
groups[n].append(m)
cache = {} # n -> list g[0..max_m_for_n] (g[0] unused)
for n, m_list in groups.items():
max_m_n = max(m_list)
# T[w] = f[w]^n (mod MOD)
T = [0] * (max_m_n + 1)
for w in range(1, max_m_n + 1):
T[w] = pow(f[w], n, MOD)
# DP for solid walls of height n
g = [0] * (max_m_n + 1)
if max_m_n >= 1:
g[1] = T[1] # always 1
for width in range(2, max_m_n + 1):
bad = 0
for k in range(1, width):
bad = (bad + g[k] * T[width - k]) % MOD
g[width] = (T[width] - bad) % MOD
cache[n] = g
# ---------- output ----------
out_lines = []
for n, m in cases:
out_lines.append(str(cache[n][m]))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()