We are given a cyclic table (i.e., toroidal) of size n x m, and a pattern of size r x c (non-cyclic). For each starting cell (i,j) in the cyclic table, we need to check if for every (x,y) in pattern (0-indexed) one of: pattern[x][y] is '?', or the cyclic table cell (i+x mod n, j+y mod m) equals pattern[x][y]. If all match, then output '1' else '0'.
We need to output an n x m grid of 0/1.
Constraints: n, m, r, c up to 400. So total table size up to 160k, pattern up to 160k. Naively for each of nm positions checking rc pattern would be O(nmrc) ~ 400^4 = 25.6e9 too high.
We need a faster method. Since the table is cyclic, we can think of using convolution or 2D pattern matching. However pattern can have '?' which match any character. This is similar to 2D pattern matching with wildcards. Could be solved using FFT (convolution) where we treat characters as numbers and use distance metric. For exact matching without wildcards, we can compute cross-correlation and check sum of squared differences. With wildcards, typical technique: For each character, treat pattern and text as binary masks, compute convolution of text and reversed pattern, etc. But we have multiple characters (26 lowercase). Usually we can use FFT with summing over characters: For each character ch, define P_ch[x][y] = 1 if pattern[x][y] == ch else 0; define T_ch[i][j] = 1 if table[i][j] == ch else 0. Then the condition for a match at (i,j) is: for each (x,y) either pattern[x][y]=='?' or T(i+x,j+y) matches pattern[x][y]. That is equivalent to: For all (x,y) where pattern[x][y] != '?', we have T(i+x, j+y) == pattern[x][y]. So we can count mismatches. For each position (i,j), we want to check if the number of mismatches is zero. Mismatch occurs if pattern cell is a specific character and table cell is different.
We could compute for each position (i,j) sum over pattern positions (x,y) where pattern[x][y] != '?': indicator(T(i+x,j+y) != pattern[x][y]). That is sum_{pattern cells} (1 - delta(T, pattern)). That's similar to 2D convolution where we compare.
We could compute convolution per character: For each character ch, define A_ch in table where it equals ch. Define B_ch as pattern mask where pattern equals ch. Then for each shift (i,j), the number of positions where pattern expects ch and table has ch is (A_ch * B_ch_rotated) convolution. So sum_{ch} that quantity = number of matches (excluding '?'). Total non-'?' cells in pattern, call P_total, is known. Then mismatch count = P_total - sum_{ch} matches. So we need mismatch == 0.
Thus we need to compute for all shifts the sum over ch of convolution of text (table) mask for ch with pattern mask for ch (but note pattern is not reversed? Actually convolution for correlation: For a shift (i,j) aligning pattern onto text such that pattern's top-left at (i,j), we want to compute sum_{(x,y)} (text[i+x][j+y] == pattern[x][y]) for pattern[x][y]!='?'. That's like sliding dot product. If we reverse the pattern (both dimensions), then convolution gives dot product. Specifically, define B_ch[x][y] = 1 if pattern[x][y] == ch else 0. Then define B_ch_rev[u][v] = B_ch[r-1-u][c-1-v]. Then the convolution (text * B_rev) at index (i,j) gives sum over (u,v) text[i-u][j-v] * B_rev[u][v] = sum over (x,y) text[i - (r-1-x)][j - (c-1-y)] * B_ch[x][y] = sum over (x,y) text[i - r +1 + x][j - c +1 + y] * B_ch[x][y]. That is offset. To get the shift where pattern's top-left at (i,j), we need to align such that for each shift (i,j) we compute sum_{(x,y)} text[i+x][j+y] * B_ch[x][y]. That's correlation, not convolution. We can achieve correlation via convolution by reversing pattern and adjusting indices. More simply, we can pad pattern to same size and use convolution with appropriate zero-padding. Since n,m up to 400, r,c up to 400, we could perform convolution via FFT of size about next power of 2 of n+r and m+c, but the total size maybe up to 1024? Actually 400+400=800, next power of 2 is 1024, which is fine. But we have 26 characters; doing 26 FFTs (each with complex numbers) could be okay: 26 * 2 (for forward transforms?) Actually we need to compute convolution for each character separately: Compute FFT of padded table for each character? That would be 26 * O(N log N) with N ~ 1024x1024 = 1e6? Actually 2D FFT on grid size (n+r-1) x (m+c-1) perhaps up to 800x800=640k, not 1e6, but still 26 * 640k * log might be okay? But we need to compute 2D FFT for each character; that's 26 transforms of the table and pattern. That's 52 2D FFTs. Since n,m <=400, we could also use brute force using bitset or other methods because 400 is moderate. There might be an O(nm + (nm)(rc)/word) approach using bitset convolution? Or using "2D string matching" with rolling hash? Because pattern size up to 400, we could treat each row as a string and do 2D Rabin-Karp? But the cyclic nature complicates? Actually cyclic table means indices modulo n,m. That's like we have an infinite tiling of the table; pattern matching on a torus. We could duplicate table to cover pattern size? Since n,m up to 400 and r,c up to 400, we could duplicate table in both directions to get a 2n x 2m? Actually pattern could be up to 400, but table size up to 400. To handle cyclic wrap, we can consider that the pattern can wrap around boundaries. For a starting position (i,j), we need to check positions (i+x mod n, j+y mod m). So effectively, we can think of the table as periodic. For each shift, we need to check against the pattern. A simple approach: For each cell (i,j) of table we want to know if pattern fits. Since n,m up to 400, total shifts = 160k. For each shift, naive checking pattern of up to 160k cells would be too high. But we can precompute something?
Given constraints are small (400), we can possibly do O(n*m * r) using bitset per row? For each shift row i, we could slide pattern across columns and use row-wise matching? Because pattern's rows are of length c, and we can match each row against the cyclic rows of the table using some string matching with '?'. Then combine across r rows.
Specifically, for each row offset x (0 <= x < r), we need to check that for each column offset y, the condition holds. For a fixed start (i,j), we need to check r rows. In each row of pattern, we need to compare a substring of length c from the table row (i+x) starting at j (cyclic). So if we preprocess for each table row, for each possible start column j, whether pattern row k matches that start. That is a 1D pattern matching with wildcard '?'. For each row of table (size m), and each pattern row (length c), we can compute a bitset or boolean array of size m indicating which starting columns j that row matches. Then for each full pattern (all r rows), we need to combine such that for each column start j, all rows simultaneously match with row offsets i+x mod n? Actually for each overall start (i,j), we need to check that for each pattern row k, the start (i+k, j) matches pattern row k. So we need to check for each i,j: for all k in [0,r-1], rowMatch[(i+k)%n][k][j] is true, where rowMatch[tableRow][patternRow][startCol] indicates pattern row patternRow matches table row at start col.
We can precompute for each table row index t (0..n-1) and each pattern row p (0..r-1) a bitset of length m indicating which j are good for that pair. Then for each overall start (i,j), we need that for all p, the bit at j in rowMatch[(i+p)%n][p] is 1. This can be done by intersecting bitsets across p. For a fixed i, we need to compute AND over p of rowMatch[(i+p)%n][p] as bitset, and output bits that are 1. Since m <= 400, we can represent each bitset as 400 bits, i.e., a bitset of 400 bits can fit in 7 64-bit words (since 400/64=6.25, so 7 words). So per rowMatch we have n * r bitsets, each of size m bits. That's nrm bits = 400400400 = 64 million bits = 8 MB, actually 64e6 bits = 8 MB (since 8 bits per byte). But we have n (table rows) times r (pattern rows) entries, each storing a bitset of m bits => n * r * m bits = 400400400 = 64e6 bits = 8 MB, that's fine. However we need to store bitsets for each (table row, pattern row). That's 160k bitsets? Actually n=400, r=400 -> 160k pairs. Each pair a bitset of m=400 bits -> total 160k * 400 bits = 64,000,000 bits = 8 MB. That's okay.
Now, for each starting row i (0..n-1), we need to compute the intersection across p=0..r-1 of bitsets rowMatch[(i+p)%n][p]. That's r AND operations on bitsets of length m. r can be up to 400, so that's 400 * (cost of AND of about 7 words) per i. n up to 400 => total operations: 400 * 400 * 7 = 1.12 million 64-bit operations, which is trivial. However we also need to compute rowMatch bitsets. How to compute rowMatch[t][p] (for table row t, pattern row p) efficiently? That's a 1D wildcard matching of pattern row string (length c) against the cyclic row of table row t (length m). We need to compute, for each start column j (0..m-1), whether pattern row matches starting at j (cyclic). That is: For each y in 0..c-1, either pattern[p][y] == '?' or table[t][(j+y)%m] == pattern[p][y]. So it's like pattern matching on a circular string with wildcards. Since m and c up to 400, we could compute for each (t,p) the match bitset naively O(m * c) = 400400=160k per pair. With nr=160k pairs, that would be 160k * 160k = 25.6e9 operations, too many. We need a faster method to compute rowMatch.
We can think of per character approach for each row. Since m and c <= 400, but we have many rows: n and r up to 400, total rows: n table rows + r pattern rows? Actually n=400, r=400, so total rows 800. So per character? Let's see: For each row pair (table row t, pattern row p) we need to compute match bitset of length m. Since we have 400x400 = 160k pairs, we can't afford O(mc) per pair because 160k * 160k = 25.6e9. But note that n and r are both up to 400, so nr = 160k is large. But maybe we can compute using convolution per row? Each row is a cyclic string of length m; pattern row length c. We need to compute for each shift j the condition that for all positions y, either pattern[p][y] is '?' or table[t][(j+y)%m] equals pattern[p][y]. This is similar to the 2D problem but 1D. For each row t and pattern row p, we could use FFT or use bitset per character across the row? Because m and c are only 400, we could use a method: For each character ch, we can compute a convolution of a binary vector for table row and pattern row reversed, and then combine. For each row pair, we'd do up to 26 convolutions? That would be even more expensive.
But we can observe that the number of distinct rows (both table rows and pattern rows) is at most 400 each. So there are at most 400 unique table rows and 400 unique pattern rows. So the number of distinct (table row string, pattern row string) pairs may be less? Actually, the table rows are given; each is a string of length m. The pattern rows are given; each is a string of length c. For each combination of a table row string and a pattern row string, we need the match bitset. Since there are n table rows (maybe duplicates) and r pattern rows (maybe duplicates). So we can precompute for each distinct table row and each distinct pattern row the match bitset once, and reuse for all pairs (t,p) that have those rows. That could reduce work if there are many duplicates. But worst-case all rows could be distinct, so still 160k distinct pairs.
But we can compute match bitset for each pair faster: Since m and c <= 400, we could use a bitset rolling approach: For each character, we could precompute a bitset for table row indicating positions where that char occurs. Then for a given pattern row, we need to check that for each position y where pattern has a specific character ch, the shifted bitset (shifted by y) matches. That is we need to compute the AND of conditions for all characters. For a given pattern row p, we can compute a bitset result that is initially all ones. Then for each character ch, consider the set of positions y where pattern[p][y] == ch (not '?'). For each such ch, we need that for every shift j, the condition that for all such y, table[t][(j+y)%m] == ch. This is equivalent to: For shift j, the condition fails if there exists a y such that pattern[p][y]==ch and table[t][(j+y)%m]!=ch. Or conversely, shift j is good if for all y with pattern[p][y]==ch, the table at j+y mod m is ch. So we can compute per character ch: Let mask_ch be a bitset of length m representing positions in table row t where character equals ch. For pattern row p, we have a set of offsets y (non-wildcard positions) for character ch. We need to compute shift j such that for all y in offsets, (j+y mod m) belongs to mask_ch. That is: j such that for every offset y, mask_ch[(j+y) mod m] is 1. That's like a set of constraints: shift j must be in the intersection over y of (mask_ch shifted left by -y?) Actually we can compute a bitset Good_ch that is initially all 1s, then for each offset y, we intersect Good_ch with (mask_ch shifted right by y) (or left). Let's derive: For a fixed offset y, the condition that table[t][(j+y) mod m] == ch is equivalent to j mod m being such that (j+y) mod m is in the set of indices where table[t] is ch. That is: j is in the set { (pos - y) mod m | pos in mask_ch }. So for each y, we compute a bitset shift_ch_y = (mask_ch rotated by -y). Then Good_ch is the AND over y of these bitsets. After processing all characters, the overall good shifts are the AND of Good_ch over all characters? Actually note: The pattern row contains multiple characters, not just one. The condition must hold for all characters simultaneously. But it's easier: The condition for shift j is that for each y (0..c-1) with pattern[p][y] != '?', table[t][(j+y) mod m] == pattern[p][y]. So we need for each character ch, for all y with pattern[p][y]==ch, the condition holds. That is equivalent to the condition that for each y, the shifted condition holds. So we could combine per character or per offset. We can also compute per character Good_ch as above, then overall Good = AND over all ch of Good_ch. But careful: What if pattern has two different characters? For each ch, Good_ch ensures that for all y with that ch, the character matches. If those constraints are independent, then the shift j must satisfy all Good_ch simultaneously, which is the intersection. So yes.
Thus we can compute for each (t,p) the good shifts as:
Initialize result bitset as all ones (size m). For each character ch (a..z):
Compute a bitset char_condition as all ones? Actually we compute a bitset that is true for shift j if for all y with pattern[p][y]==ch, table[t][(j+y)%m] is ch.
Then result &= char_condition.
Now, to compute char_condition efficiently: For a given table row t, we have mask_ch (length m bits) indicating positions where the row has char ch. For pattern row p, we have a list of offsets y where it expects ch. If that list is empty, char_condition = all ones (no constraint). If nonempty, we need to compute the intersection over these offsets of (mask_ch rotated by -y). That is:
Let B = mask_ch. For each offset y, compute B_y = rotate_right(B, y) (or rotate left? need to check: We want shift j such that (j+y)%m is in B, i.e., B[(j+y) mod m] = 1. So if we define B shifted by -y (circularly), i.e., B'[j] = B[(j+y) mod m]? Actually if we take mask_ch and rotate it left by y, then the value at index j in rotated mask is mask_ch[(j - y) mod m] (if rotate left by y means shift indices -y). Let's define rotation such that after rotation, at index j we have the value originally at (j+y) mod m? Actually we can define: For a given offset y, we want a bitset R_y where R_y[j] = 1 iff B[(j+y)%m] = 1. That's B rotated right by y (since index j maps to j+y). In circular bitset terms, rotate left by y would give B[(j - y) mod m] at j. So we need rotate_right by y. However, we can compute by rotating mask_ch accordingly.
Thus char_condition = AND over y (rotate_right(mask_ch, y)). However, we need to compute this intersection efficiently. Since m is only 400, we can actually compute char_condition by iterating over j from 0 to m-1 and checking conditions? That would be O(m * (number of offsets)) per char. In worst case, pattern row length c up to 400, and for a given ch it could have up to 400 offsets. For each pair (t,p) and each character, we could compute char_condition in O(m * num_ch_offsets). That might be too heavy if we do it for all pairs. But note: For each (t,p) we would loop over all 26 characters, and for each ch with offsets, we loop over j and check each offset? That would be O(26 * m * c) per pair worst-case, which is again large.
But we can compute char_condition using bitset operations: For each offset y, we have a bitset R_y = rotate_right(mask_ch, y). To compute intersection across multiple offsets, we can start with all ones bitset, and for each offset, AND with R_y. That would be O(num_ch_offsets * (m/word)) per char. With m=400, bitset AND takes about 7 64-bit operations. So per offset, cost is low. So for each (t,p) we could do: For each character ch (1..26) get the list of offsets for pattern row p for that ch. Then compute temp = all_ones bitset. For each offset y in that list, temp &= rotate_right(mask_ch[t], y). After processing all offsets for that ch, if temp is not empty we AND to result. This would cost per (t,p) sum over characters of (#offsets for that ch in pattern row p) * (cost of rotate_right and AND). Since total #offsets across all chars for a pattern row p is exactly the number of non-'?' characters in that row, which is <= c (<=400). So per (t,p) we would have at most c rotations and ANDs. And each rotation+AND on bitset of length m takes O(m/word) ~ 7 operations. So per pair cost is O(c * (m/word)) ~ 4007 = 2800 operations. For 160k pairs, that's 160k * 2800 ≈ 448 million simple bit operations. This might be borderline but perhaps okay in C++ with optimization? 448 million 64-bit ops is maybe okay (less than 1e9). However we also need to compute rotate_right for each offset. But we can precompute for each table row t and each character ch the mask bitset. And rotation can be done by shifting and OR (circular shift). Implementing circular shift of bitset of size m (400) is cheap; we can precompute for each table row t and character ch, and each shift amount y (0..c-1) the rotated mask? That would be huge: n * 26 * c bitsets => 40026*400 ≈ 4.16 million bitsets each of 400 bits => 4.16M * 400 bits = 1.664e9 bits = 208 MB, too high. So we cannot precompute all rotated masks.
But we can compute rotation on the fly using bitset operations like left/right shift with wrap. Since m is small, we can implement a circular bitset using two 64-bit integers? Actually m=400, we can store bitset as an array of 7 uint64_t (or use std::bitset<400>). std::bitset<400> has shift operators but they are not circular. We can implement circular shift manually: To rotate right by y, we can do (bitset << (m-y)) | (bitset >> y) but careful with sizes. For bitset of fixed size, bitset shift left shifts bits to higher indices, but the bits that go beyond size are dropped. So to simulate circular shift, we can do ((bitset << (m-y)) | (bitset >> y)) & full_mask. However if we use std::bitset, we can use to_ullong()? Not for 400 bits. But we can implement our own using array of 64-bit words. Because m=400, we can store as 7 words. Circular shift by y can be implemented by shifting the word array with wrap. This is doable but we need to do it many times. But we can perhaps avoid per-offset rotation by using convolution with bitset? Another approach.
But maybe we can compute rowMatch more efficiently by using FFT for each row? However given the moderate constraints, the above O(nrc * (m/word)) might be okay if implemented carefully. Let's compute more precisely:
n=400, r=400 => 160k pairs. For each pair, we process each non-'?' character position in pattern row (c_max=400). So total operations: sum over (t,p) of (#non-'?' in pattern row p). But pattern row p is fixed for each p; across all t we process same pattern row many times. For each t, we process pattern row p's non-'?' positions. So total non-'?' accesses across all pairs = n * (total non-'?' over all pattern rows) = n * (r*c - number of '?'). In worst case, pattern has no '?', so total = n * r * c = 400^3 = 64 million. That's 64 million positions. For each such, we need to do a rotation+AND on a bitset of size m (400 bits). But we can perhaps precompute for each table row t and each character ch, the mask bitset. For a given pattern row p, we need to for each non-'?' at offset y with char ch, compute rotated mask and AND. That means each such operation involves reading the mask bitset for that t and ch, rotating it by y, and ANDing into a temporary bitset. The rotation operation: To rotate right by y, we can precompute for each t and ch, the mask as a bitset. Rotating by y can be done by (mask << (m-y)) | (mask >> y) (with proper bit handling). But since m=400, we can store mask in 7 64-bit words. Implementing a circular shift of a bitset of 400 bits by a variable amount might be somewhat heavy but still okay for 64 million operations? 64 million rotations of 400-bit bitsets might be too heavy. But maybe we can reduce.
Instead of rotating per offset, we could precompute for each table row t and each character ch, a representation that allows quick query of whether for a given shift j and offset y, table[t][(j+y)%m] == ch. That is essentially we need to evaluate for each j, check all offsets. We could compute rowMatch for each (t,p) by scanning j from 0 to m-1 and checking each offset? That would be O(m * c) per pair, which is 160k * 400*400 = 25.6e9, too heavy.
We can use bitset convolution or FFT per row? Since m and c <= 400, we could compute rowMatch for a given t and pattern row p using a 1D convolution per character similar to the 2D approach but on a single row. For each character ch, we can compute a convolution of the row (binary) and reversed pattern row (binary). Using FFT for each row individually would be expensive: For each t and p we would need to run 26 FFTs? No.
But we can exploit that the number of distinct rows is only 400 each. For each distinct pair (table row string, pattern row string) we compute rowMatch once. But worst-case all rows distinct: still 400 distinct table rows and 400 distinct pattern rows, so 160k distinct pairs. But we can try to compute rowMatch for all pairs using a more global method: For each character ch, we can treat each table row as a binary vector of length m, each pattern row as a binary vector of length c. We need, for each combination of table row index t and pattern row index p, to compute a vector (bitset) of length m that indicates for each shift j whether for all y where pattern row p has ch at y, the table row t has ch at (j+y). This is like a "for all" condition, not sum. However the condition "for all y, B[(j+y)%m]==1" where B is mask for ch, and the set of y is given. That's equivalent to: j is such that for each y in set Y, B[(j+y)%m]==1. This is the intersection of the sets S_y = { j : B[(j+y)%m]==1 } = { (pos - y) mod m | B[pos]==1 }. So it's the set of shifts j that are equal to (pos - y) for some pos? Wait careful: For a single offset y, the set of j for which condition holds is the set of j such that B[(j+y)%m]==1. That's exactly the set of j = (pos - y) mod m for any pos where B[pos]==1. So that set is just the mask B rotated left by y (since if we rotate B left by y, the element at index j becomes B[(j+y)%m]? Actually rotate left by y: (B << y) | (B >> (m-y)). That gives at index j: originally B[j] moves to (j-y) mod m. So we need rotate right by y to get condition B[(j+y)%m]. Let's derive: Suppose we have a bitset B of length m. Define R = rotate_right(B, y) such that R[j] = B[(j+y) mod m]. Then condition B[(j+y) mod m] == 1 is equivalent to R[j]==1. So the set of j that satisfy is exactly the positions where R has 1. So for a given offset y, the set of valid j is rotate_right(B, y). So as earlier.
Thus char_condition = intersect_{y in Y} rotate_right(B, y). So we need to compute intersection of several rotated copies of B. This can be done via bitset operations.
But we can optimize by precomputing for each table row t and character ch, all rotated versions of mask_ch? That would be m rotations, each of m bits, total n * 26 * m * m bits? That's 40026400400 = 1.664e9 bits again ~208 MB? Wait: For each (t,ch), there are m possible rotations (0..m-1). Each rotation is a bitset of length m. That would be n * 26 * m * (m/8) bytes = 400 * 26 * 400 * 50 = 40026=10400, times 400 = 4,160,000, times 50? Let's calculate: m=400, so each bitset is 400 bits = 50 bytes. Number of such bitsets: n (400) * 26 * m (400) = 40026400 = 4,160,000 bitsets. Times 50 bytes = 208,000,000 bytes = 208 MB. That's high but maybe acceptable? 208 MB is borderline but maybe okay in C++ if we use memory optimization (like bitset<400>). std::bitset<400> typically uses 400/8=50 bytes? Actually std::bitset stores N bits, typically using an array of unsigned long (maybe 64-bit). For N=400, it would use ceil(400/64)=7 words = 56 bytes (if 64-bit). So 4.16M * 56 = ~233 MB. That's too high for typical memory limit (likely 256 MB? Usually Codeforces 256 MB). Could be too close and also time for constructing 4.16M rotations might be high. But we could compress: For each t and ch, we only need rotations by offsets that appear in pattern rows. Since pattern rows have at most c=400 offsets, but across all pattern rows, the offsets are from 0..c-1 (c <= 400). So for each t,ch, we need at most c distinct rotations (0..c-1). Actually we need rotations by y for any y that appears in any pattern row as a non-'?' position. Since there are r pattern rows, each with up to c positions, total offsets set is still 0..c-1 (if pattern rows can have any offset). But c <= 400. So for each (t,ch) we only need to precompute rotations for y from 0 to c-1 (max 400). That's the same as m if m > c? But m could be up to 400, so c is up to 400. So still 400 rotations per (t,ch). So still 4.16M rotations. So memory 200+ MB maybe okay but risky. Let's compute more precisely: n=400, alphabet size=26, c_max=400 -> 40026400 = 4,160,000 rotations. Each rotation is a bitset of size m=400 bits -> 50 bytes if packed. That's 208 MB. With overhead of vector storage etc, might exceed. Possibly we can compress further: since m=400, we can store each rotation as a bitset<400> in an array of 64-bit words (7 words). 78=56 bytes => 4.16M56 = 233 MB. Plus other data, might be >256 MB. Could we use a different representation? Maybe we don't need to store all rotations; we can compute them on the fly using bitwise operations that are cheap enough for 64 million operations (64 million rotations). Each rotation of a 400-bit bitset can be done with shift and OR across words. That's not too heavy. Let's estimate: 64 million rotations, each doing say 10-20 integer operations (shifts, OR, masking). That's about 1 billion operations, might be okay in optimized C++ within time (2 seconds? Possibly borderline). But we can reduce the number of rotations: For each (t,p) we need to process each non-'?' position. That's total n * (total non-'?') = n * (rc - #?). In worst case, if pattern has no '?', that's nr*c = 64 million. So 64 million rotations and ANDs. That's the number we computed. So we might directly implement without precomputation, but we need to implement rotate_right efficiently.
We can implement bitset of size 400 as std::bitset<400>. However std::bitset does not have built-in circular shift. But we can simulate using combination of left shift and right shift and mask: For rotate right by y: (bs << (m - y)) | (bs >> y) and then mask with all ones (bits 0..m-1). Since std::bitset supports shift, but shift is not circular; but we can do exactly that: auto rot = ((bs << (m-y)) | (bs >> y)); However shift operators for std::bitset truncate bits outside range. For left shift, bits shifted beyond size are discarded; for right shift, bits shifted beyond size are discarded. So (bs << (m-y)) will shift left by (m-y), bringing lower bits to higher indices, and bits beyond m-1 are lost. But we want wrap-around. Actually for circular right shift by y: we want bits that go off the right end to come in from left. In terms of left/right shift, we can do: (bs >> y) | (bs << (m-y)). Wait: For right circular shift by y: new[i] = old[(i+y) mod m]. If we take (bs >> y), then new[i] = old[i+y] for i+y < m, else 0. (bs << (m-y)) gives new[i] = old[i-(m-y)] for i >= m-y, else 0. So OR of these yields circular right shift. So formula: rot = (bs >> y) | (bs << (m - y)). Then we must mask to only bits 0..m-1. But std::bitset<400> automatically discards bits beyond 399 for shift? Actually left shift beyond size discards, but it doesn't wrap; but we want the bits that were shifted out to appear at low indices. Using (bs << (m-y)) will shift bits to indices >= m-y, and bits that go beyond m-1 are discarded. However in (bs << (m-y)), the bits that originally were at indices < y? Let's check with example m=8, y=3. bs = b7b6b5b4b3b2b1b0 (index 7 is MSB? but we treat index 0 LSB). Right circular shift by 3: new[0] = old[3], new[1]=old[4], new[2]=old[5], new[3]=old[6], new[4]=old[7], new[5]=old[0], new[6]=old[1], new[7]=old[2]. Compute (bs >> 3): gives new'[0]=old[3], new'[1]=old[4], new'[2]=old[5], new'[3]=old[6], new'[4]=old[7], new'[5]=0, new'[6]=0, new'[7]=0. Compute (bs << (8-3)=5): gives new''[0]=0,..., new''[5]=old[0], new''[6]=old[1], new''[7]=old[2]. OR yields correct. So formula is (bs >> y) | (bs << (m-y)). For bitset size m, shift operators only keep bits within [0,m-1]. So that works. So we can compute rotate_right using this expression. For std::bitset<400>, this involves two shifts and an OR, which should be efficient. Then we AND with another bitset. So per offset operation involves constructing rotated bitset and AND. That's cheap.
Thus per (t,p) we can do: result = all ones bitset. For each character ch from 'a'..'z':
if pattern row p has any positions with ch (we can store list of offsets per pattern row per ch)
then compute temp = all ones bitset? Actually we need char_condition = intersection over offsets of rotate_right(mask_ch, y). So we can start with temp = all ones bitset; then for each offset y in list, temp &= rotate_right(mask_ch_t, y). After processing all offsets for that ch, result &= temp.
But careful: The condition requires that for each non-'?' position, the character matches. So per character, we need to ensure that for all y where pattern[p][y]==ch, the table has ch. The above intersection ensures that. Then we also need to consider that for different characters, we need all to hold, so we AND across characters.
But we can also compute result directly: Initialize result = all ones; for each non-'?' position (y, ch) in pattern row p, we do result &= rotate_right(mask_ch_t, y). That's simpler: For each position (y, ch) (non-'?'), we intersect result with rotate_right(mask_ch_t, y). Because the condition must hold for every such position. This eliminates the per-character grouping; we just iterate over all non-'?' positions (up to c) and each time AND with the appropriate rotated mask. That is even simpler and doesn't need grouping by char. So for each pattern row p, we can store a vector of pairs (y, ch-index). Then for each table row t, we compute result bitset = all ones; for each (y, ch) in pattern row's non-'?' positions: result &= rotate_right(mask_ch[t], y). That yields the set of shifts j where row t matches pattern row p.
Thus total operations per (t,p) = number of non-'?' positions in pattern row p (<= c) times (rotate_right + AND). So total operations across all pairs = n * (total number of non-'?' over all pattern rows). Since total non-'?' across pattern rows = r * c - count('?'), worst case 160,000 (since r and c up to 400). Actually r*c maximum is 160k. So total non-'?' across pattern rows ≤ 160k. So n * (total non-'?') ≤ 400 * 160k = 64 million. That's 64 million iterations. Each iteration: for a given t, ch, y, we need to get mask_ch[t] (bitset for table row t and character ch) and compute rotate_right of that bitset by y, then AND into result. rotate_right can be computed as (mask >> y) | (mask << (m - y)). Since we do this for many (t,p) pairs, we would be repeatedly rotating the same mask for same t, ch, y many times across different p? Not necessarily: For each table row t, we will process each pattern row p. For each p, we will process its non-'?' positions. So for a given (t,ch), the same y may appear in multiple pattern rows? Possibly. So total rotations across all pairs may be up to 64 million. That's okay.
But we need to store mask_ch for each table row and each character. That's n26 bitsets of size m = 40026=10400 bitsets, each 400 bits => 10400 * 50 = 520k bytes, negligible.
We also need for each pattern row p, a list of (y, ch-index) of non-'?' cells. That's total ≤ r*c entries, ≤ 160k.
Now, for each t from 0..n-1, we need to compute for each p from 0..r-1 a bitset good_shifts[t][p]. That's n*r bitsets, each 400 bits, 64 million bits = 8 MB, which is fine.
We can compute rowMatch[t][p] as described.
Then for each overall start (i,j) (i row in table, j col), we need to check if for all p, rowMatch[(i+p)%n][p] has j set. We can compute for each i, a bitset result_i = all ones initially, then for p=0..r-1: result_i &= rowMatch[(i+p)%n][p] (circular row indexing). Finally output result_i bitset for that row i. Complexity: n * r AND operations on bitsets, each AND cost ~7 64-bit ops. n=400, r=400, total 160k ANDs, cheap.
Thus overall algorithm:
-
Input n,m, table rows strings.
-
Input r,c, pattern rows strings.
-
Preprocess table: For each row t (0..n-1), for each character ch (0..25), create a bitset mask[t][ch] where mask[t][ch][j] = 1 iff table[t][j] == ch. We'll store as std::bitset<400> or custom bitset. Since m<=400, we can use std::bitset<400>; but m is given, not constant 400? Actually m up to 400, but we can use std::bitset<400> and only use first m bits. We'll need to ensure shift operations respect m. For rotation we use m (actual width). Since m may be less than 400, we need to treat bits beyond m as zero to avoid incorrect wrap? Using std::bitset<400>, we can set bits only up to m-1. Shifts will shift bits within the 400-bit container. For rotation, we use (mask >> y) | (mask << (m - y)). But mask << (m - y) will shift bits to higher indices; if m < 400, bits that go beyond index m-1 could spill into indices >= m, but that's okay because those bits represent wrap positions? Actually we need circular rotation modulo m, not modulo 400. We must ensure that when we rotate, bits that go beyond m-1 wrap to lower indices, but we also must not allow bits outside 0..m-1 to affect result because they are not part of the row. So we need to mask after rotation to only keep bits 0..m-1. However, the rotation formula using shifts on bitset of size 400 may incorrectly include bits that were originally beyond m? Initially mask only has bits set within [0,m-1]. After shifting left by (m - y), bits will move to indices >= m - y. For example, if m=400, it's fine. If m < 400, say m=200, and we shift left by (m-y) which is up to 200, bits originally at index 0..m-1 can be shifted to indices up to (m-1)+(m-y) <= 2m-1, which may be less than 400. Some of those bits will land in indices >= m, which in the rotation should wrap to lower indices. However our formula (mask >> y) | (mask << (m - y)) will produce bits in higher indices that should actually be wrapped into lower indices. But the OR of the two parts: (mask >> y) gives bits at indices where original index+y < m? Actually (mask >> y) moves bits to lower indices (right shift). Bits originally at high indices (>= y) become indices-y. Bits originally at indices < y are shifted out and lost. That part is correct because those bits should wrap to high indices? Wait, we need circular right shift by y: new[j] = old[(j+y)%m]. Let's test with m=5, using bitset of size 5? Suppose we have bitset of size 5: indices 0..4. mask = 00101 (bits: index0:1? Let's not get confused). Better to use standard: index0 LSB. For m=5, we have bits at positions 0..4. Rotate right by 2: new[0] = old[2]; new[1]=old[3]; new[2]=old[4]; new[3]=old[0]; new[4]=old[1]. Compute (mask >> 2): shifts bits right: old[2]->index0, old[3]->index1, old[4]->index2, old[0],old[1] lost. So we get bits at indices 0,1,2 correct for new[0..2]. Compute (mask << (5-2)=3): shifts left by 3: old[0]->index3, old[1]->index4, old[2]->index5 (out of range), old[3]->index6, old[4]->index7. Since bitset of size 5 (or larger), but we only have 5 bits, so bits beyond 4 are discarded if we consider only lower 5 bits? In std::bitset<5>, left shift by 3: bits that go beyond 4 are lost, so we lose old[2],old[3],old[4] and keep old[0] at index3, old[1] at index4. So OR gives indices 3 and 4 correct. So for m=5, it works if we use bitset of size exactly m. If we use a larger bitset (like 400) but only set bits within 0..m-1, then after left shift by (m-y), bits can go into indices >= m, which are not part of the row, but they should actually wrap to lower indices? However, our rotation is defined modulo m. If we have a bitset with capacity larger than m, we need to ensure that bits that go beyond m-1 wrap around modulo m. Using the formula (mask >> y) | (mask << (m - y)) with a bitset of size larger than m will not correctly wrap because bits shifted left beyond m-1 may end up in indices beyond m-1, but we need them to appear in lower indices (since we OR with the right shifted part, those bits already cover lower indices? Let's analyze: Suppose we have bitset of size M > m, but we only care about bits in range [0, m-1]. The rotation we want yields bits only in that range. Starting with mask having bits only in [0, m-1]. When we compute (mask << (m - y)), bits originally at position i will go to i + (m - y). For i in [0, m-1], the resulting position may be in [m-y, 2m-y-1]. Some of these may be >= m. For those >= m, they should wrap to i + (m - y) - m = i - y. But notice that (mask >> y) already gives bits at positions i - y for i >= y (since right shift yields i - y). Actually, (mask >> y) gives bits at positions (i - y) for i >= y, and bits for i < y are lost. The bits that from left shift that end up at positions >= m correspond to original indices i where i + (m - y) >= m => i >= y. So those bits would be at positions i + (m - y). But we need them at positions (i + (m - y)) mod m = i - y, which are already covered by the right shift for i >= y? Let's see: For i >= y, right shift already gives a 1 at i - y (from original i). However, left shift may also produce a 1 at some index > m, which we should ignore. For i < y, left shift gives i + (m - y) which is in range [m - y, m-1]? Since i < y, i + (m - y) is in [m - y, m - 1 + (y-?)]. Actually max i = y-1, so max i + (m - y) = (y-1) + (m - y) = m-1. So for i < y, left shift gives positions in [m - y, m-1] exactly. These are within [0, m-1] because m-1 >= m - y. So for i < y, left shift yields positions in the range [m-y, m-1], which are the high part of the target range. For i >= y, left shift yields positions i + (m - y) which are >= y + (m - y) = m, so these go beyond m-1. However, those bits should be at positions i - y (since i - y = (i + m - y) - m). But those positions are already covered by the right shift for i >= y? Right shift gives bits at positions i - y for i >= y. So the left shift for i >= y would be redundant (and would land outside the range). So if we use a bitset of size larger than m and we only look at bits in [0, m-1], the left shift for i >= y does not affect the low range because they go beyond m-1. So the formula (mask >> y) | (mask << (m - y)) works correctly as long as we mask to m bits after OR. Because the left shift for i >= y produces bits above m-1 that we ignore, while right shift for i >= y produces the needed bits. Left shift for i < y produces bits in high part of [0,m-1]. Right shift for i < y produces nothing. So overall, we get correct rotation if we restrict to bits 0..m-1. However, if we use a bitset of size M > m, after left shift, bits may land in indices >= m but still be within M. If we later AND this rotated bitset with another bitset that only has bits in [0,m-1], those extra bits will be zero (since other bitset only has bits in [0,m-1]), but they could affect if we later do further operations? Actually we will AND rotated bitset with result bitset, which is also only defined for bits 0..m-1 (others zero). But if rotated bitset has bits set beyond m-1, they will be ANDed with zero, so no effect. However, they could cause the rotated bitset to have ones outside range, but when we later AND with result (which only has bits in range), the extra bits are irrelevant because result's bits outside range are zero. But if we later use the same rotated bitset for further ANDs, it may keep those extra bits as 1, but they will be ANDed with zero later so they become zero anyway. So it's okay if rotated bitset has extra bits beyond m-1 set; they won't affect final result because we only care about bits 0..m-1. However, when we later do result &= rotated, the rotated bitset may have 1 bits outside range, then result's bits outside range (which are initially 1? result initially is all ones for all 400 bits if we use bitset<400> with all bits set. That would cause a problem because we would be requiring that bits beyond m-1 also match? But we only care about shifts j in 0..m-1. So we should ensure that our result bitset only has bits 0..m-1 considered. We can initialize result as all ones but then after each operation we can mask to m bits? Alternatively, we can set bits beyond m-1 to zero initially and keep them zero. Since our pattern matching only concerns columns 0..m-1, we can just ignore higher bits. But if result initially is all ones (all 400 bits set), and we AND with rotated bitset that might have bits beyond m-1 set to 1 (maybe) or 0? Actually rotated bitset may have some bits beyond m-1 set to 1 (due to left shift). For i < y, left shift yields positions in [m-y, m-1], all within 0..m-1 if m-y >=0. For i >= y, left shift yields positions >= m, which could be within 0..399 if m < 400. For example, m=200, y=10, i=150: i + (m - y) = 150+190=340 <400, so bit 340 becomes set. That's beyond m-1 (199). So rotated bitset would have bit 340 set. Then when we AND with result (all ones initially), result would keep bit 340 as 1. Later when we intersect across pattern rows, the result bits beyond m-1 will remain 1 because no operation will clear them (unless some rotated mask has zero there). But those bits correspond to shift indices >= m, which we don't care about. However, we only output bits 0..m-1. If result has bits beyond m-1 set to 1, that's fine because we ignore them. But we must ensure that those bits do not affect the AND for bits within 0..m-1. They don't, because AND is per-bit independent. However, when we later compute final result_i and output only first m bits, the extra bits are irrelevant. So it's okay to keep them as they are. However, we need to be careful: When we initialize result bitset for rowMatch[t][p], we want it to be all ones for all bits 0..M-1 (M=400). But then for each non-'?' position, we AND with rotated mask. The rotated mask may have some bits beyond m-1 set to 1 (if m<400). But we only care that for bits j in 0..m-1, the condition holds. For j >= m, those positions are not valid column shifts because columns indices are modulo m, only 0..m-1 exist. So we could just ignore them. However, we should ensure that for those j>=m, the result bits after all ANDs remain 1 (since we don't care). That's fine; they will be 1 if all rotated masks have 1 there. But rotated masks might have 0 there, causing those bits to become 0, but we don't care. So we can simply not worry about bits beyond m-1; we just extract lower m bits when outputting.
But there is a subtlety: When we rotate mask (which has bits set only in [0,m-1]), the rotated bitset may have bits set in [0, M-1] that correspond to the circular wrap modulo m. However, if m < M, the rotation defined by (mask >> y) | (mask << (m - y)) with M bits may not produce correct circular rotation for bits beyond m-1 because we are effectively doing rotation within M bits, but we want rotation modulo m. Let's check with m=3, M=5. Suppose mask has bits at positions 0,1,2. We want circular right shift by 1 within m=3: new bits should be at positions: new[0] = old[1], new[1]=old[2], new[2]=old[0]. So bits at positions 0,1,2. Our method with M=5: (mask >> 1) gives: old[1]->0, old[2]->1, others 0. (mask << (3-1)=2) gives: old[0]->2, old[1]->3, old[2]->4. OR yields bits at 0,1,2,3,4. Bits at 3 and 4 correspond to old[1] and old[2] shifted left. But for j=3