We are given two binary matrices A (size na x ma) and B (size nb x mb). We consider shifts (x,y) such that we align B onto A: we place B so that its cell (i+x, j+y) corresponds to A's cell (i,j). Actually the definition: overlap factor S(x,y) = sum_{i,j} A[i][j] * B[i+x][j+y] where indices must be valid in both matrices. That is, i from max(1, 1-x) to min(na, nb-x), j from max(1, 1-y) to min(ma, mb-y). So the overlapping region depends on shift.
We need to find (x,y) maximizing S. x and y can be any integers (including negative) but effectively only those where overlapping region non-empty? Actually we need to consider all possible shifts, including those with no overlap (S=0). But it says first table has at least one 1, second has at least one 1. Maximum S could be 0 if no overlapping ones match? But it's possible to get positive if some ones align. However, if there is no overlap region (i.e., the ranges are empty), then S=0. So maximum S is at least 0. But since there is at least one 1 in each, maybe there is possibility of positive? Actually could be that overlapping region has no 1-1 matches; but S is sum of product (both 1) -> maximum at least 0. But we might get positive if we align a 1 from A onto a 1 from B. But we could also get negative? No, product is 1*1=1, else 0. So non-negative.
Goal: find (x,y) achieving maximum sum.
Constraints: na, ma, nb, mb <= 50. So total cells up to 2500. Brute force all possible shifts? Overlap region is limited: we only need to consider x such that there is any overlap: -nb+1 <= x <= na-1? Actually for B to overlap A, we need some i such that 1 <= i <= na and 1 <= i+x <= nb. So i ranges from max(1,1-x) to min(na, nb-x). For there to be at least one i, we need max(1,1-x) <= min(na, nb-x). This yields constraints on x. The possible x values such that overlap exists: x can range from - (nb-1) to (na-1) (since i and i+x must be in bounds). Let's derive: i ranges from 1 to na. i+x must be from 1 to nb. So i must satisfy 1-x <= i <= nb-x. Also 1 <= i <= na. So i must lie in [max(1, 1-x), min(na, nb-x)]. For existence, need max(1,1-x) <= min(na, nb-x). That is equivalent to -nb+1 <= x <= na-1 (maybe inclusive). Check: If x = na-1, then i max is min(na, nb-(na-1)) = if nb-(na-1) >= 1? Usually it's possible if nb>=1. But we need existence: choose i=na, then i+x = na+na-1 = 2na-1, which is > nb maybe; but i must be <= nb-x = nb-(na-1). For existence, we need na <= nb-x? Actually condition: max(1,1-x) <= min(na, nb-x). Let's test x large positive: x=na, then i can be at most min(na, nb-na). If nb-na < 1? Then min maybe 0? Actually na positive. Condition: max(1,1-na) = 1, min(na, nb-na). For existence need 1 <= min(na, nb-na). That requires nb-na >= 1 => nb >= na+1. But if nb=na, then min(na,0) = 0 => fails. So x = na is not allowed unless nb > na. Actually general valid x range: -nb+1 <= x <= na-1? Let's test x = na-1: then min(na, nb-(na-1)): if nb-(na-1) >= 1; that's always true because nb>=1 and na-1 <= na-1, but nb may be less than na-1? For x=na-1, nb-x = nb - (na-1) = nb - na +1. If nb=1, na=3: nb-x = 1-2 = -1 -> min(na, -1) = -1? Actually min(na, negative) is negative, but i lower bound max(1, 1-x)= max(1, 1-(na-1))= max(1,2-na) = 1 (since 2-na <=0). So we need 1 <= negative? Not possible. So x=na-1 is not allowed if nb - na +1 < 1, i.e., nb - na +1 <= 0 => nb <= na-1. For na=3, nb=1, x=2 => nb-x = -1, indeed no overlap. So the range of x such that overlap exists is: x from max(-(nb-1), - (na?)? Actually we can think: the overlapping region exists if the two intervals [1, na] and [1-x, nb-x] (for i) intersect. Interval for A's i: [1, na]. Interval for B's i after shift: B's original row indices are 1..nb, but after shift we align B's cell (i+x, j+y) with A's (i,j). Actually B's row index in overlapping region is i+x. For given x, B's rows that align correspond to i+x for i satisfying A's rows. Alternatively, the overlapping rows correspond to rows that are common between A and B after shift: rows r such that r is in [1, na] and r+x is in [1, nb] => r in [1, na] ∩ [1-x, nb-x]. So non-empty intersection when 1 <= nb-x and na >= 1-x? Not exactly. Intersection exists if max(1, 1-x) <= min(na, nb-x). So we need to solve for x that satisfy this inequality.
But given the small sizes, we can simply iterate over all x and y that could produce any overlap. The maximum number of possible x values is (na + nb - 1)? Because if we slide one matrix over the other, the number of distinct overlapping positions along rows is na + nb - 1 (x from -(nb-1) to (na-1)). Similarly for columns: ma + mb - 1. So total shifts with potential overlap is at most (na+nb-1)(ma+mb-1) <= (99)(99) = 9801, which is fine. Actually maximum: na,ma,nb,mb <=50, so na+nb-1 <= 99, ma+mb-1 <= 99 => at most 9801 shifts. For each shift, compute sum over overlapping region O(overlap area). Overlap area at most min(na,nb) * min(ma,mb) <= 2500. So worst-case operations: 9801 * 2500 ~ 24.5 million, which is okay in C++ but maybe borderline in Python? 24.5 million operations with nested loops and indexing is okay in Python if optimized (list of ints, using boolean? but still fine). But we can also use convolution-like methods (FFT) but not needed.
But note: The problem states x and y can be any integers, even those where there is no overlap (S=0). But we need to output a shift with maximum overlap. If maximum S is 0, we need to output any shift that gives 0. Could be a shift with no overlap. But also shifts with overlap might give 0 as well. So we should consider all possible shifts, including those with no overlap, but we can restrict to those with overlap because those might give higher sums. However, we must also consider shifts that produce zero overlap factor but maybe other shifts with zero? But maximum is zero, any shift giving zero is acceptable. But if there is any positive sum, it will be >0, so we need to output a shift giving positive. So we can compute only shifts with non-empty overlap because those are the only ones that could be positive; but it's possible that all overlaps give zero, but some may have empty region? Actually empty region yields zero, same as some overlapping region with no matching ones. So if all S are zero, any shift works, including empty ones. But if we only compute shifts with overlap, we might find that all those give zero, but still maximum is zero. However, we need to output a shift. Could output (0,0) if it's valid? But maybe (0,0) might give zero? That would be fine. But to be safe, we can also consider all possible shifts. However, we need to output any shift among those with maximum S. So we can compute all shifts with overlap, record max S, and if max S > 0, output that shift; else if max S == 0, we need to output any shift (including maybe one with no overlap). But we can just output (0,0) in that case, but need to ensure that (0,0) may be within the range? (0,0) might not be within overlap? Actually (0,0) always gives overlap region as intersection of the two matrices (if they intersect). If both matrices have at least one cell each, (0,0) may have overlap if na>=1 and nb>=1, which they are. Actually (0,0) yields i from 1 to min(na,nb), j from 1 to min(ma,mb). So overlap exists. So S(0,0) is computed. If all S computed (including (0,0)) are zero, then we can output (0,0) as a valid shift with max (0). But is it possible that (0,0) gives zero but some shift with no overlap yields also zero, both are max. But (0,0) is acceptable. So we can just compute all x from -(nb-1) to (na-1) and y from -(mb-1) to (ma-1). That's total (na+nb-1)*(ma+mb-1) shifts. Then we can compute S for each and track max. That's simple.
But careful: The problem states |x|,|y| <= 1e9 in output, but they can be any integers. So we can output any of these shifts.
Implementation details:
-
Read input.
-
Represent A as list of strings? But we need numeric 0/1 for multiplication. Could convert to list of list of ints.
-
For each x in range(-(nb-1), na) (since na-1 inclusive, but range in Python uses stop exclusive). Actually x can be from -(nb-1) to (na-1). So x_min = -(nb-1), x_max = na-1. So iterate for x in range(-(nb-1), na). (since na-1 inclusive, use na as stop? Actually range(start, stop) where stop is not included. So if we want up to na-1 inclusive, set stop = na. Because range(-(nb-1), na) will include values from -(nb-1) up to na-1. Test: na=3, range(-(nb-1), 3) includes - (nb-1) .. 2 (since stop=3). That's correct because na-1=2. So x_max = na-1, stop = na. Similarly y from -(mb-1) to ma-1, so range(-(mb-1), ma). That yields all possible overlaps.
-
For each (x,y), compute sum. Overlap rows: i from max(1, 1-x) to min(na, nb-x) inclusive. Similarly j from max(1, 1-y) to min(ma, mb-y). So we can compute start_i = max(0, -x) if using 0-index? Could convert to 0-index to simplify? Let's define A as 0-indexed: rows 0..na-1, columns 0..ma-1. B rows 0..nb-1, cols 0..mb-1. Then shift (x,y) aligns A[i][j] with B[i+x][j+y]? Wait careful: The original definition: S = sum_{i,j} A[i][j] * B[i+x][j+y] where indices 1-indexed: 1 <= i <= na, 1 <= j <= ma, 1 <= i+x <= nb, 1 <= j+y <= mb. Convert to 0-index: let i' = i-1, j'=j-1. Then condition: 0 <= i' <= na-1, 0 <= j' <= ma-1, 0 <= i'+x <= nb-1, 0 <= j'+y <= mb-1. Because i+x becomes (i'+1)+x? Actually careful: i is 1-indexed row index in A, i+x is 1-indexed row index in B. So when i=1 => A row 0. B row index = (i+x) - 1 = (1+x)-1 = x. So the mapping: A's 0-index row i0 corresponds to B's 0-index row i0 + x? Let's derive: i (1-index) in A => i0 = i-1. Then B's row is i+x (1-index) => B0 = (i+x)-1 = i-1 + x = i0 + x. So indeed, shift (x,y) in terms of 0-index means that A cell at (i0, j0) aligns with B cell at (i0 + x, j0 + y). However the condition for valid alignment is: 0 <= i0 <= na-1, 0 <= j0 <= ma-1, 0 <= i0 + x <= nb-1, 0 <= j0 + y <= mb-1. So the overlapping region: i0 from max(0, -x) to min(na-1, nb-1 - x). Similarly j0 from max(0, -y) to min(ma-1, mb-1 - y). Then sum = sum over those i0, j0 of A[i0][j0] * B[i0+x][j0+y].
So we can compute start_i = max(0, -x); end_i = min(na-1, nb-1 - x); if start_i > end_i, no overlap => sum=0. Similarly for j. Then nested loops.
Given small sizes, it's fine.
Edge Cases: The output shift can be any with max overlap. If multiple, print any.
We should ensure we consider all shifts. However, might there be shifts outside that range that produce higher sum? If there is no overlap, sum=0. So any shift with no overlap gives sum 0. So the maximum is either >0, achieved by some overlap shift, or =0, achieved by any shift. But we are already considering all overlaps (which include those giving positive or zero). If all overlaps give zero, then the maximum is 0 and any overlap shift (like (0,0)) gives 0, so it's fine to output that. So we don't need to consider shifts outside overlap range because they also give 0, but the maximum is 0 anyway and we already have a candidate shift (the first we consider or any overlap shift) giving 0. However, what if there is an overlap shift that gives zero, but a non-overlap shift also gives zero, both are max. It's fine to output an overlap shift. So we can restrict to the range described. But ensure that if there is a positive maximum, it must be within these ranges because overlapping is required for positive sum. So it's safe.
But what about shifts where overlapping region exists but the sum is zero? That's considered. So we will find max among all such shifts.
Complexity: worst-case (na,nb,ma,mb=50) => x range: from -49 to 49 => 99 values; y similar => 99 => 9801 shifts. For each shift, overlap area at most 5050 = 2500. So up to 24.5 million product and sum operations. In Python, with nested loops inside loops, that's maybe borderline but likely fine if optimized using list comprehensions? 24.5 million integer multiplies and additions is doable within 1-2 seconds in CPython? Let's estimate: 24 million operations may take ~0.5-1 second if well-coded (pure Python loops might be slower). Actually Python's for loops are relatively slow; 24 million inner loop iterations may be too slow if we do triple nested loops: for x, for y, for i, for j. That could be 9801 * 2500 = 24.5M inner loop bodies. Each body includes index accesses and multiplication. 24.5M might be okay if using Python with moderate optimization (like using built-in sum over generator) but still could be borderline 2-3 seconds. Usually Codeforces problems with n=50 allow O(n^4) ~ 6.25M? Actually 50^4 = 6.25 million. Here we have 1001005050 = 25 million? Yes 25M. Python can handle 25M simple operations in < 2 seconds? Possibly but not certain. We can attempt to optimize by using bitsets or convolution? But given it's a Codeforces problem (I recall problem "A and B and Interesting Substrings"? Not sure). But I've seen solutions in Python that brute force with O(nanbmamb) = up to 50^4 = 6.25M? Wait careful: The number of shifts is (na+nb-1)(ma+mb-1). In worst-case, na=ma=50, nb=mb=50 => 99*99 = 9801 ~ 10^4. Overlap area up to min(na,nb)*min(ma,mb) = 2500. So product = 2.5e7. That's more than 6.25M. However, there is also the fact that the sum over i,j for each shift can be computed efficiently using convolution using FFT? But that might be overkill. But we can perhaps reduce complexity by precomputing something, like for each possible relative shift we can compute dot product.
Observation: The sum S(x,y) = sum_{i,j} A[i][j] * B[i+x][j+y] over overlapping region. This is essentially the cross-correlation of two binary matrices. Since sizes are small, we could compute it by iterating over all pairs of 1 positions. Alternative method: For each pair of a '1' in A and a '1' in B, they contribute 1 to S(x,y) when the shift aligns them. Specifically, if A has a 1 at (i0, j0) (0-index) and B has a 1 at (i1, j1), then the shift (x,y) that aligns these two is x = i1 - i0, y = j1 - j0. Then for that shift, the product A[i0][j0]*B[i1][j1] = 1 contributes to S(x,y). So we can compute S for all shifts by iterating over all 1s in A and B, and increment count for shift (i1-i0, j1-j0). But careful: The shift (x,y) may align more than one pair of 1s; we need to sum contributions. So we can have a dictionary mapping (x,y) to count. Then the maximum count over all shifts, we output that shift. However, we need to consider also that for a given shift, there may be overlapping region where some positions are not both 1; but we only count pairs of 1s. That is exactly S(x,y) because S is sum over overlapping cells where both are 1. And each pair of 1 cells that align under that shift contributes exactly 1. But we must ensure that the overlapping region includes the cells, and we are not double counting: if a shift aligns two 1s at the same positions, that's a contribution. However, what about cases where multiple pairs from A and B align? Actually each overlapping cell corresponds to a specific (i,j) pair (the A coordinate and the B coordinate via shift). For a fixed shift (x,y), each overlapping coordinate i,j yields a product A[i][j] * B[i+x][j+y]. So the sum is number of overlapping cells where both are 1. This is exactly the number of pairs (i,j) such that A[i][j]=1 and B[i+x][j+y]=1, with i, j in overlapping range. If we consider all possible 1 positions in A (p) and in B (q), a given shift (x,y) will be such that for each 1 in A at (i0,j0), we need a 1 in B at (i0+x, j0+y) for a contribution. So the contribution count is the number of 1s in A such that the corresponding shifted position is a 1 in B. That's equivalent to: For shift (x,y), S(x,y) = |{ (i0,j0) in A's ones : (i0+x, j0+y) is a 1 in B and within bounds }|. So if we enumerate all pairs of 1s (a from A, b from B), then for each pair we get a candidate shift (dx = b.i - a.i, dy = b.j - a.j). For that shift, that particular a contributes to S if the shifted position of a falls exactly on b, which is true. But note: For a given shift, there might be multiple a that map to multiple b. If we simply count the number of pairs (a,b) that yield that shift, that gives exactly S(x,y) because each a that maps to a b under that shift corresponds to a distinct overlapping cell (since a's positions are distinct). However, caution: Could there be two different a1, a2 both mapping to the same b under the same shift? That would require a1 != a2 but a1 + (x,y) = b and a2 + (x,y) = b => a1 = a2, so impossible. Also could there be an a that maps to a b that is not in B? No, we only consider pairs where b is a 1 in B. So indeed, for a given shift (x,y), the set of (a,b) pairs with b - a = (x,y) is in one-to-one correspondence with the set of a such that A[a]=1 and B[a+(x,y)]=1. So S(x,y) equals the number of such pairs. Therefore, we can compute S for all shifts by iterating over all 1s in A and B, compute dx = iB - iA, dy = jB - jA, and increment count for (dx,dy). The maximum count over all (dx,dy) will be the answer, provided that we also consider shifts that yield zero? But if no pairs exist, max count = 0. Then any shift works, but we still need to output a shift. In that case, the dictionary might be empty. So we need to handle that.
However, note: The shift (dx,dy) computed from a pair might not be a valid shift? Actually it can be any integer, possibly large? But from the pair, dx = iB - iA, where iA in [0, na-1], iB in [0, nb-1], so dx ranges from -(na-1) to (nb-1). That's within the range we considered earlier: -(nb-1) to (na-1)? Actually dx can be as low as - (na-1) if iB=0, iA=na-1 => dx = - (na-1); as high as nb-1 if iB=nb-1, iA=0 => dx = nb-1. That's a broader range: from -(na-1) to (nb-1). But earlier we said x range for overlap is from -(nb-1) to (na-1). Which is symmetric? Actually (na-1) vs (nb-1). They are swapped. Let's compare: Overlap range: x_min = -(nb-1) (because if x = -(nb-1), then i0 min = max(0, -x) = max(0, nb-1) = nb-1, which must be <= na-1? Actually condition for existence: start_i <= end_i, which yields x between max(-(nb-1), - (na-1)? Not exactly. Wait we derived earlier using 1-index: x from -(nb-1) to (na-1). But that might be incorrect. Let's derive properly with 0-index.
We want shifts x such that there exists i0 with 0 <= i0 <= na-1 and 0 <= i0+x <= nb-1. That is i0 in intersection of [0, na-1] and [-x, nb-1 - x]. The interval [-x, nb-1 - x] is just the set of i0 such that i0+x is in [0, nb-1]. For intersection to be non-empty, we need max(0, -x) <= min(na-1, nb-1 - x). So that's the condition. Solve for x. The extremes: The intersection exists when -x <= na-1 and 0 <= nb-1 - x, i.e., x >= - (na-1) and x <= nb-1? Actually from -x <= na-1 => x >= - (na-1). From 0 <= nb-1 - x => x <= nb-1. So we have x >= - (na-1) and x <= nb-1. But also need max(0, -x) <= min(na-1, nb-1 - x). For x in that range, is it automatically satisfied? Not always. Let's test na=1, nb=1. Then condition: x >= 0? -(na-1)=0, and x <= 0 (nb-1=0). So x=0 is possible. That works. If na=1, nb=2: x >= 0, x <= 1. Check x=1: Then i0 must satisfy 0 <= i0 <= 0 (since na-1=0) and 0 <= i0+1 <= 1 => i0 in [-1,0]. Intersection is i0=0 (since 0 in both). So x=1 works, even though earlier range said up to na-1=0? So earlier was wrong. So correct x range where overlap can exist is: x_min = - (na-1)? Actually check x negative: If na=2, nb=1: Then x must satisfy x >= -(na-1)= -1, x <= nb-1 = 0. Check x = -1: i0 in [0,1] and i0-1 in [0,0] => i0 in [1,1] (since i0-1 >=0 => i0 >=1; and <=0 => i0 <=1). So i0=1 works. So x=-1 works. So indeed x ranges from - (na-1) to nb-1 inclusive. But is that the full range? Let's test na=2, nb=2: x from -1 to 1. Check x=1: i0 in [0,1] and i0+1 in [0,1] => i0 <=0? Actually i0+1 <=1 => i0 <=0. So i0 in [0,0] works. So x=1 works. Check x=-1 works similarly. So the full range for possible overlap is: - (na-1) <= x <= nb-1. Similarly y: - (ma-1) <= y <= mb-1. However, do all x in that range guarantee some overlap? Need to verify if there always exists i0 satisfying both. For given x, the condition max(0, -x) <= min(na-1, nb-1 - x) must hold. Let's analyze the lower bound: max(0, -x). The upper bound: min(na-1, nb-1 - x). For the inequality to hold, we need both:
-
max(0, -x) <= na-1 (obviously true since max(0,-x) <= max(na-1?) Not guaranteed: if -x > na-1? Then max(0,-x) = -x, and we need -x <= na-1, i.e., x >= -(na-1). So that gives x >= -(na-1).
-
Also max(0, -x) <= nb-1 - x. Consider two cases: If x >= 0, then max(0,-x)=0, condition 0 <= nb-1 - x => x <= nb-1. If x < 0, then max(0,-x) = -x, condition -x <= nb-1 - x => -x <= nb-1 - x => add x both sides: 0 <= nb-1, true. So for x<0, condition reduces to x >= -(na-1) (as above). So overall condition is x >= -(na-1) and x <= nb-1. Also need that min(na-1, nb-1 - x) is at least something, but we've captured. So indeed the necessary and sufficient condition for existence of some overlapping row is x in [-(na-1), nb-1]. Similarly for columns: y in [-(ma-1), mb-1]. So the number of possible x values is (nb-1) - (-(na-1)) + 1 = na + nb - 1. That's consistent with earlier count 99. But earlier we incorrectly set the range as -(nb-1) to (na-1). That's symmetric but swapped. Actually (na-1) and (nb-1) are not necessarily equal. So the correct range is from -(na-1) to nb-1. Let's verify with example: na=3, nb=2. Then na-1=2, nb-1=1. Range: -2 <= x <= 1. Earlier brute force often uses x from -(nb-1) to (na-1) which would be -1 to 2. That's different. Which one is correct for overlapping? Let's test with na=3 (rows 1-3), nb=2 (rows 1-2). Overlap possibilities: shift x such that some row aligns. We'll enumerate manually:
-
x= -2: Then A row i=3 aligns with B row i+x=1? i=3 => B row 1, ok. So overlapping row exists (i=3). So x=-2 works. Our range -2 to 1 includes -2, the earlier ( -1 to 2 ) does not include -2. So earlier range is missing some shifts. Indeed, if B is smaller, we can shift B upward (negative x) such that its bottom row aligns with top row of A? Actually with shift (x,y), A's row i aligns with B's row i+x. For x negative, i+x < i. To have any overlap, we need some i such that i in [1,na] and i+x in [1,nb]. The smallest possible x is when we align the top of B with bottom of A: i = na, i+x = 1 => x = 1 - na = -(na-1). So x_min = -(na-1). Largest x when align bottom of B with top of A: i = 1, i+x = nb => x = nb - 1. So indeed x_max = nb-1. So the range is [- (na-1), nb-1]. So earlier I swapped. Good to correct. Similarly for y.
Therefore, when enumerating all possible shifts with potential overlap, we should iterate x from -(na-1) to nb-1 inclusive, and y from -(ma-1) to mb-1 inclusive. That yields (na+nb-1)*(ma+mb-1) shifts, same count.
Now, the pair enumeration method: For each 1 in A (iA,jA) and each 1 in B (iB,jB), the shift (dx = iB - iA, dy = jB - jA) is in the range: dx from -(na-1) to nb-1, dy from -(ma-1) to mb-1. So it's within that range. So we can compute counts for each such shift. Then the maximum count among these shifts corresponds to the maximum S, because any shift with positive S must have at least one pair of 1s aligning, so its count will be at least that positive number. Actually is it possible that a shift (dx,dy) yields a positive S but is not represented by any pair? Wait if S(x,y)>0, then there exists at least one (i,j) such that A[i][j]=1 and B[i+x][j+y]=1. That yields a pair (i,j) and (i+x, j+y). So the shift (x,y) will be generated from that pair. So indeed any shift with positive S will be present in the dictionary (maybe multiple times). So the maximum S among all shifts is exactly the maximum value in the dictionary (if any positive). If the dictionary is empty (i.e., no pair of 1s), then S(x,y) = 0 for all shifts (since there are no 1-1 overlaps; but could there be a positive S if no pair? No, because S is sum of products, product=1 only when both are 1). If there is no pair of 1s (meaning either A has no 1? But problem guarantees at least one 1 in each, but they might be arranged such that for any overlap shift, the specific overlapping cells that are both 1 never occur? Actually it's possible that A has ones, B has ones, but in every possible alignment, the ones never align because they are positioned such that no shift brings a 1 onto a 1. Example: A: 1x1 matrix with 1 at (1,1). B: 1x1 matrix with 1 at (1,1). Actually that aligns at shift (0,0) giving 1, so pair exists. To have no pair, need that for every possible shift, no 1 from A aligns with a 1 from B. Is that possible? With at least one 1 in each, consider A has a 1 at (1,1), B has a 1 at (2,2) in a 2x2? Then shift (1,1) aligns them: (iA=1,jA=1) -> B(2,2) gives shift (1,1) which is valid? iA=1 => iB = 1+1=2 (within B's rows), jB=2 within cols, so yes. So pair exists. Could we avoid? If A's 1 is at top-left, B's 1 at bottom-right, the shift needed is positive; but if B's dimensions are smaller? Let's think: A 2x2: 1 at (2,2). B 2x2: 1 at (1,1). Then shift x = 1-2 = -1, y = 1-2 = -1. That is within range? x=-1, y=-1. Overlap exists? For x=-1, iA must be such that iA-1 is in [1,2], i.e., iA in [2,2]? Actually iA=2 works: iA=2 => B row 1. So yes. So it seems with at least one 1 each, there will always be some shift aligning them? Not necessarily: Suppose A is 1x2: row1 col1=1, col2=0. B is 2x1: row1 col1=0, row2 col1=1. Then the possible shifts: x from -(na-1)=0 to nb-1=1 (since na=1 -> na-1=0 => x_min=0, x_max=1). y from -(ma-1)= -(1)?? ma=2 => ma-1=1 => y_min=-1, mb=1 => mb-1=0 => y_max=0. So y range -1..0. Let's check possible shifts: (x,y) pairs: (0,-1): align A (1,1) with B (1,0) invalid because B col index 0? Actually B columns 1..1, so j+y must be between 1 and 1. For A (1,1), j=1,y=-1 => B col 0 invalid. (0,0): A (1,1) aligns with B (1,1) but B[1,1]=0 -> product 0. A (1,2) aligns with B (1,2) out of range? Actually j=2,y=0 => B col2 invalid. So shift (0,0) overlapping region? We need to check valid i,j. Overlap rows: i from max(1,1-x) =1 to min(na, nb-x)= min(1,2-0)=1 => i=1. Overlap cols: j from max(1,1-y)=max(1,1-0)=1 to min(ma, mb-y)=min(2,1-0)=1 => j=1 only. So only A[1,1] and B[1,1] considered, both not 1? A[1,1]=1, B[1,1]=0 => product 0. So S=0. Next shift (0, -1): Overlap rows: i=1; cols: j from max(1,1-(-1))=max(1,2)=2 to min(2,1-(-1)=0) => min(2,0)=0 => start>end, no overlap => S=0. Shift (1,0): Overlap rows: i from max(1,1-1)=max(1,0)=1 to min(1,2-1=1)=1 => i=1; cols: j from max(1,1-0)=1 to min(2,1-0=1)=1 => j=1. Then A[1,1]=1, B[1+1,1+0]=B[2,1]=1 => product 1. So S=1. So there is a pair (A(1,1), B(2,1)) with shift (1,0). Indeed dx=2-1=1, dy=1-1=0, which is within range. So there is a shift with positive S. It seems if both have at least one 1, there will always be some shift that aligns them? Consider extreme: A has 1 at (1,1), B has 1 at (1,1). Then shift (0,0) works. If the 1 in B is at some position that is not reachable by any shift such that the overlapping region includes that pair? But the shift that directly aligns the two ones is x = iB - iA, y = jB - jA. For that shift to be valid, we need that for the specific iA, jA, the corresponding B position is within bounds (by definition it is), but also that the overlapping region includes that cell. However, the overlapping region for that shift includes at least the cell (iA, jA) because: iA satisfies 0<=iA<=na-1, and iA + x = iB, which is within 0..nb-1. So it is included. So any pair of 1s yields a valid shift with at least that cell overlapping. So indeed, if both matrices have at least one 1, there exists at least one pair? Not exactly; we need that the same pair (iA,jA) and (iB,jB) exist. But we can choose any 1 from A and any 1 from B; there is at least one each, so there is at least one pair, so there is at least one shift (the difference) that yields positive S (>=1). Wait but does the shift (dx,dy) necessarily have overlapping region that includes that pair? Yes, as argued, iA is in [0, na-1], iA+dx = iB in [0, nb-1]. So the cell is included in the overlapping region because both indices are within bounds. However, we also need that for that shift, the overlapping region is defined as all i,j where both indices are in bounds. The cell (iA, jA) satisfies both. So it is counted in S(dx,dy). So S(dx,dy) >= 1. So maximum S is at least 1. Therefore, if both matrices have at least one 1, the maximum overlap factor is positive. That is true? Let's double-check: Could it be that the shift (dx,dy) leads to overlapping region, but the sum is just that one product? Yes, it's at least 1. So the maximum S is positive. But wait the problem statement: "It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1"." So indeed there is at least one 1 in each. So there will always be a shift with S >= 1 (just align that 1 from A with that 1 from B). So maximum S >= 1. But sample 1 output had shift (0,1) with some value presumably >0. Sample 2: A is 3x3 with a single 1 in the middle, B is 1x1 with 1. So maximum S is 1? The output is (-1,-1). Let's check: For sample 2, na=3, ma=3, A: row2 col2=1 (0-index? Actually A: row2 col2? The input: 000, 010, 000 => center is 1). B: 1. Then the shift that aligns B's single 1 with A's 1 is: need x such that iA + x = 0 (0-index) for the B cell? Actually B is 1x1, so its only cell is at (0,0) (since 1-index row1 col1). To align with A's 1 at (1,1) (0-index), we need x = iB - iA = 0-1 = -1, y = 0-1 = -1. So shift (-1,-1) yields S=1. That matches output. So indeed positive.
Thus we don't need to worry about zero maximum.
Hence the pair enumeration method works and is efficient. Complexity: number of ones in A (p) times number of ones in B (q). In worst case, both matrices could be all ones: p = nama <= 2500, q = nbmb <= 2500, product = 6.25 million. That's about 6.25 million increments. That's more efficient than 25 million with nested loops per shift. So the pair method is better.
But careful: The shift (dx,dy) computed from a pair may be same for many pairs, and we count them. That gives S(dx,dy) exactly because for each aligning pair of ones, there is a distinct A cell that maps to a distinct B cell. However, is it possible that for a given shift, the same A cell could align with two different B cells? No, because shift defines a unique mapping from A cells to B cells: each A cell maps to exactly one B cell (if within bounds). So each pair (a,b) with b = a + (dx,dy) corresponds to exactly one overlapping cell. So count of such pairs equals S(dx,dy). There is no double counting or missing because any overlapping cell where both are 1 gives a pair. So the method is correct.
Potential issues: The shift (dx,dy) may be such that some other A cells that are 1 do not have B counterpart, but that's okay; we are only counting matches. So the dictionary maps (dx,dy) to number of matched 1 cells. The maximum over dictionary yields the answer.
But we must also consider that there might be shifts where S(dx,dy) > 0 but the dictionary entry exists, so we capture it. However, could there be a shift that yields a positive sum but is not generated by any pair? No, because if there is any overlapping cell with both ones, that gives a pair. So all positive shifts appear.
Edge case: What if the same shift (dx,dy) appears from multiple pairs? That's fine; we increment.
Thus algorithm:
-
Parse input, store positions of ones in A and B as lists of (i, j) using 0-index.
-
Initialize a dictionary (defaultdict(int)) counts.
-
For each (iA, jA) in onesA:
For each (iB, jB) in onesB:
dx = iB - iA
dy = jB - jA
counts[(dx, dy)] += 1
-
Find the (dx, dy) with maximum count. In case of tie, any is fine.
-
Print dx and dy (as integers).
But wait: The output expects x and y as defined in the problem statement, which are the same as our dx, dy? In our 0-index mapping, we have S(x,y) = sum_{i,j} A[i][j] * B[i+x][j+y]. So yes, x = dx, y = dy.
So output dx and dy.
But verify with samples:
Sample 1:
A:
3x2:
01
10
00
=> ones: (0,1) (since row1 col2? Let's index 0: row0: "01" -> (0,1) is 1; row1: "10" -> (1,0); row2: "00" -> none. So onesA = [(0,1), (1,0)].
B:
2x3:
001
111
=> onesB: parse row0: "001" -> (0,2); row1: "111" -> (1,0),(1,1),(1,2). So onesB = [(0,2), (1,0), (1,1), (1,2)].
Compute pairs:
-
(0,1) with (0,2): dx=0-0=0, dy=2-1=1 -> count (0,1) ++
-
(0,1) with (1,0): dx=1-0=1, dy=0-1=-1 -> (1,-1)
-
(0,1) with (1,1): dx=1, dy=0 -> (1,0)
-
(0,1) with (1,2): dx=1, dy=1 -> (1,1)
-
(1,0) with (0,2): dx=-1, dy=2 -> (-1,2)
-
(1,0) with (1,0): dx=0, dy=0 -> (0,0)
-
(1,0) with (1,1): dx=0, dy=1 -> (0,1)
-
(1,0) with (1,2): dx=0, dy=2 -> (0,2)
Now counts: (0,1) appears twice (from first pair and seventh pair). Others once. So max count = 2 for shift (0,1). Output (0,1). Matches sample.
Sample 2:
A ones: (1,1) (0-index) because row2 col2? Actually 3x3, row index 1 (0-index) for second row, col index 1 for second column.
B ones: (0,0) only.
dx = 0-1 = -1, dy = 0-1 = -1. Count = 1. So output (-1,-1). Matches.
So algorithm works.
But we must be careful about memory: counts dictionary size: at most pq distinct shifts, but maximum distinct shifts is bounded by (na+nb-1)(ma+mb-1) <= 9801, which is small. So dictionary fine.
Implementation steps:
-
Read na, ma.
-
Read A lines, for each line, for each char, if '1', store (i, j).
-
Read nb, mb.
-
Similarly store onesB.
-
Use dictionary (or a 2D array with offset). Since ranges are small, we could use a 2D array indexed by dx and dy with offsets. dx range: from -(na-1) to (nb-1). dy range: from -(ma-1) to (mb-1). So we can allocate array of size (na+nb-1) x (ma+mb-1). But easier with dict.
-
Iterate over onesA and onesB, update counts.
-
Find max count and corresponding (dx,dy). If multiple, pick any (first encountered).
-
Print dx dy.
But there is a nuance: The shift (dx,dy) computed from a pair is always within the range of possible shifts that have overlapping region, because both iA and iB are within bounds, so dx is between -(na-1) and (nb-1) indeed. So we can output that.
Edge Cases: Very large number of ones (2500 each) -> loops 6.25M, which is fine in Python. However, we need to ensure that inner loop is efficient: use for loops and dict increment. That should be okay.
But we should also consider that there might be cases where the dictionary method yields the correct maximum but we must also ensure that the shift we output indeed gives the computed sum; but that's fine.
One more nuance: Are there any shifts that yield a higher S than the count of pairs? No, because S = number of overlapping ones matches, which is exactly the number of pairs that satisfy b = a + shift. So our method directly computes S for all shifts that have at least one such pair. But what about shifts that have zero matches? Those have S=0 and are less than any positive, so not needed.
Thus answer is correct.
Potential Pitfalls: The shift (dx,dy) we output might be such that the overlapping region includes some cells where A has 1 but B has 0, but that's irrelevant; we maximize sum of matches.
Check against sample 1: we got (0,1) with count 2. Let's compute S(0,1) manually: Overlap rows: i from max(1,1-0)=1 to min(na, nb-0)= min(3,2)=2 => i=1,2. Columns: j from max(1,1-1)=1 to min(ma, mb-1)= min(2,3-1=2)=2 => j=1,2. So overlapping 2x2 region. A matrix (1-index): row1: 0 1, row2: 1 0, row3: 0 0. B matrix: row1: 0 0 1, row2: 1 1 1. For shift (0,1), B rows align: A row1 with B row1? Actually i=1: B row 1+0=1, j: A col1 -> B col 1+1=2 => A[1,1]=0, B[1,2]=0? B[1,2]=0? Wait B row1: 0,0,1 => col2=0. So product 0. A[1,2] (j=2) -> B col3 => 1 => A[1,2]=1, B[1,3]=1 => product1. Next i=2: A row2 col1=1, B row2 col2=1 => product1. A row2 col2=0, B row2 col3=1 => 0. Sum=2. Yes.
So works.
Implementation details:
-
Use sys.stdin.read() or input().
-
Represent ones as list of tuples.
-
Use collections.defaultdict(int).
-
For max, we can iterate over items.
Time complexity: O(p*q). In worst-case p=q=2500, 6.25M. Each iteration does a few arithmetic ops and dict access. Should be within time.
But we can potentially speed up by using array with offsets to avoid dict overhead. But it's fine.
Now we must output x and y. Note: In sample output, they printed "0 1". That's the shift as defined. So we output dx, dy.
But confirm: In problem statement, x and y can be any integers, |x|,|y| <= 1e9. Our dx, dy will be within [-49,49], so valid.
Thus solution is straightforward.
But wait, is it always correct? Let's double-check with a scenario where there are multiple 1s aligning but the overlapping region includes also some cells where both are 1 but the shift is not represented by a pair? That is impossible.
But consider the following: For shift (dx, dy), the sum S is over overlapping cells (i,j) with A[i][j]=1 and B[i+dx][j+dy]=1. That is exactly the number of pairs (i,j) such that (i,j) is in onesA and (i+dx, j+dy) is in onesB. This is exactly the count we compute by iterating over all pairs (a,b) where a in onesA, b in onesB, and checking if b - a = (dx,dy). So we can map each (dx,dy) to the count of a such that a+(dx,dy) in onesB. That's exactly a convolution-like operation. So our dictionary gives those counts. The maximum over dictionary is the maximum S.
One nuance: For a given shift, there might be overlapping cells where both are 1 but the pair (a,b) is counted, but also there might be overlapping cells where both are 1 but we didn't count because? No, each such cell gives a pair (a,b). So all counted.
Thus correct.
Potential edge: If the same shift (dx,dy) appears from pairs, we sum them. That yields S.
Therefore, we can implement.
Now I'll craft the solution.
Implementation plan:
import sys
from collections import defaultdict
def main():
data = sys.stdin.read().split()
it = iter(data)
na = int(next(it))
ma = int(next(it))
A = []
onesA = []
for i in range(na):
row = next(it).strip()
A.append(row) # maybe not needed
for j, ch in enumerate(row):
if ch == '1':
onesA.append((i,j))
nb = int(next(it))
mb = int(next(it))
onesB = []
for i in range(nb):
row = next(it).strip()
for j, ch in enumerate(row):
if ch == '1':
onesB.append((i,j))
counts = defaultdict(int)
for iA, jA in onesA:
for iB, jB in onesB:
dx = iB - iA
dy = jB - jA
counts[(dx, dy)] += 1
# Find max
max_val = -1
best_dx = best_dy = 0
for (dx, dy), val in counts.items():
if val > max_val:
max_val = val
best_dx, best_dy = dx, dy
# Note: Since both have at least one 1, counts non-empty, max_val >=1.
print(best_dx, best_dy)
if __name__ == "__main__":
main()
Testing with sample:
Input:
3 2
01
10
00
2 3
001
111
Will output 0 1, as expected.
But note: The reading of rows: after reading na, ma, we read na lines, each may be given as separate tokens? In the data splitting by whitespace, each line is a token. That's fine.
Edge: There might be spaces in the lines? The lines contain only '0' and '1' characters, no spaces. So splitting works.
Now confirm with sample 2:
3 3
000
010
000
1 1
1
Output: -1 -1.
Works.
Now consider a case with multiple maximum. We'll output the first encountered, which is fine.
Thus solution is ready.
But let's double-check the range of x: from -(na-1) to nb-1 inclusive. That's the range of shifts that can produce any overlap. Our dictionary may produce shifts only within that range because iA in [0, na-1], iB in [0, nb-1] => dx in [ - (na-1), nb-1 ]. So consistent.
Thus correct.
Now think about potential oversight: The problem statement says "Print two space-separated integers x, y (|x|, |y| ≤ 109) — a shift with maximum overlap factor. If there are multiple solutions, print any of them." So any shift with maximum overlap factor. Our method gives a shift that maximizes number of overlapping 1s. However, is it possible that there is a shift that yields a higher sum but is not represented in the dictionary? That would require that there is a shift where S>0 but no pair (a,b) with b-a = shift. But if S>0, there is at least one cell where both are 1, giving such a pair. So it's represented.
Thus correctness.
Time complexity: O(onesA * onesB) <= 6.25e6, dictionary operations about that many. Should run within 1 second in Python? Possibly. On Codeforces, Python can handle ~10^7 simple operations with some overhead. 6.25 million increments with dict might be okay. But we can micro-opt: Use a plain 2D array sized (na+nb-1) x (ma+mb-1) and map dx,dy to indices with offset. This would be faster because array indexing is faster than dict. But dict may be fine. However, to be safe, especially with Python, using list of lists with offsets might be more efficient. Let's evaluate: na+nb-1 <= 99, ma+mb-1 <= 99 => array of size up to 99x99 = 9801. That's small. So we can allocate a 2D list of zeros, using dx offset = na-1 (since dx min = -(na-1), so index = dx + (na-1)). But careful: dx max = nb-1, so size should be (na-1 + nb-1 + 1) = na+nb-1. So offset_x = na-1. Similarly offset_y = ma-1. Then we can do:
size_x = na + nb - 1
size_y = ma + mb - 1
offset_x = na - 1
offset_y = ma - 1
counts = [[0]*size_y for _ in range(size_x)]
Then for each pair:
dx = iB - iA
dy = jB - jA
ix = dx + offset_x
iy = dy + offset_y
counts[ix][iy] += 1
Then find max by scanning the matrix. This will be faster because array access is O(1) and scanning is cheap.
We must be careful: dx can be negative up to -(na-1), so ix = dx + (na-1) ranges from 0 to (nb-1)+(na-1) = na+nb-2? Let's check max dx = nb-1, so ix max = nb-1 + na-1 = na+nb-2, which is size_x - 1 because size_x = na+nb-1 => indices 0..na+nb-2. Yes. Similarly for dy.
Thus using array is straightforward and efficient.
We should also note that counts[ix][iy] will never go out of bounds because dx, dy are within those ranges. However, we should verify that for any pair (iA,iB), dx = iB - iA satisfies iB in [0,nb-1], iA in [0,na-1] => dx_min = 0 - (na-1) = -(na-1), dx_max = (nb-1) - 0 = nb-1. So it's safe.
Thus we can implement with array.
Pseudo:
dx_min = -(na-1)
dx_max = nb-1
dy_min = -(ma-1)
dy_max = mb-1
size_x = dx_max - dx_min + 1 = nb-1 + na-1 + 1 = na+nb-1
size_y = dy_max - dy_min + 1 = ma+mb-1
offset_x = -dx_min = na-1
offset_y = -dy_min = ma-1
counts = [[0]*size_y for _ in range(size_x)]
for iA,jA in onesA:
for iB,jB in onesB:
dx = iB - iA
dy = jB - jA
ix = dx + offset_x
iy = dy + offset_y
counts[ix][iy] += 1
Then find max.
We can store best during updates to avoid second scan? But scanning small array is fine.
Now note: The answer is shift (dx, dy) not the indices. So we output dx, dy.
Potential tie: we want any, we can break on first encounter of max.
We need to be careful that the maximum may be 0? But as argued, since both have at least one 1, there will be at least one shift with count >=1. So max >=1. So we don't need to handle zero case.
Now confirm with sample 1: na=3 => offset_x = 2; size_x = 3+2-1=4. Actually na+nb-1=4, indices 0..3. dx min = -(na-1)= -2, max = nb-1 = 1. So -2,-1,0,1. offset=2 => dx=0 -> ix=2; dx=1->3; dx=-1->1; dx=-2->0. Similarly for y: ma=2 => offset_y=1; size_y=2+3-1=4? Actually ma+mb-1=2+3-1=4, indices 0..3. dy min = -(ma-1) = -1, max = mb-1=2 => -1,0,1,2. offset_y=1 => dy=0->1; dy=1->2; dy=-1->0; dy=2->3. Our computed counts: (0,1) appears twice -> dx=0,dy=1 => ix=0+2=2, iy=1+1=2 => counts[2][2]=2. That will be max.
Thus output: 0 1.
Now edge case: maybe the dictionary method is simpler but I'll implement array for speed.
One more nuance: Input reading: After reading na, ma, we read na lines. Each line may be read as a token. So we can use sys.stdin.readline() in a loop to get lines directly. That might be simpler.
I'll implement:
import sys
def main():
import sys
input = sys.stdin.readline
na, ma = map(int, input().split())
onesA = []
for i in range(na):
line = input().strip()
for j, ch in enumerate(line):
if ch == '1':
onesA.append((i,j))
nb, mb = map(int, input().split())
onesB = []
for i in range(nb):
line = input().strip()
for j, ch in enumerate(line):
if ch == '1':
onesB.append((i,j))
offset_x = na - 1
offset_y = ma - 1
size_x = na + nb - 1
size_y = ma + mb - 1
counts = [[0]*size_y for _ in range(size_x)]
for iA, jA in onesA:
for iB, jB in onesB:
dx = iB - iA
dy = jB - jA
ix = dx + offset_x
iy = dy + offset_y
counts[ix][iy] += 1
max_val = -1
best_dx = best_dy = 0
for ix in range(size_x):
row = counts[ix]
for iy in range(size_y):
val = row[iy]
if val > max_val:
max_val = val
best_dx = ix - offset_x
best_dy = iy - offset_y
print(best_dx, best_dy)
But note: This will output the first encountered max (since we scan rows from 0 to size_x-1, and columns 0 to size_y-1). That's fine.
But need to ensure that when we compute offset_x = na - 1, that corresponds to dx_min = -(na-1). Since offset_x = -dx_min? dx_min = -(na-1) => -dx_min = na-1. Yes.
Now confirm with sample 2: na=3 => offset_x=2; size_x=3+1-1=3? Wait nb=1 => na+nb-1 = 3+1-1=3. dx_min = -(na-1) = -2, dx_max = nb-1 = 0. So dx can be -2, -1, 0. offset_x=2 => indices: -2->0, -1->1, 0->2. So size_x=3, indices 0,1,2. good. Similarly, ma=3 => offset_y=2; mb=1 => size_y=3+1-1=3? Actually ma+mb-1=3+1-1=3. dy_min=-2, dy_max=0. indices: -2->0, -1->1, 0->2. Pair: (1,1) - (0,0) gives dx=-1, dy=-1 => ix = -1+2=1, iy = -1+2=1 => counts[1][1] = 1. Scanning yields max_val=1 at ix=1,iy=1 => best_dx = 1-2 = -1, best_dy = -1. Good.
Thus answer.
Now consider performance: The nested loops over onesA and onesB: worst-case 2500 * 2500 = 6.25M. Inside, we do simple arithmetic and array increment. That's fine.
Time: In Python, 6.25M iterations may take around 0.2-0.3 seconds? Actually typical Python can do about 30-50 million simple operations per second? Not sure. But 6.25M is comfortable. We also have scanning of ~10k cells for max, trivial.
Thus solution is efficient and simple.
Now I'll also consider if any shift might be optimal but not generated by any pair? As argued, no.
But wait, there's a subtlety: For a given shift, the overlapping region might have cells where both A and B have 1, but the shift might also align cells that are not within the overlapping region? No, overlapping region is exactly those cells where both indices are valid. So it's fine.
Thus final solution.
Double-check with a custom case: A all ones, B all ones. Then for any shift that yields overlapping region, S = number of overlapping cells (since all ones). The maximum S would be maximum overlapping area. The overlapping area as function of shift: area = (na - |dx|?) Actually rows overlap count = number of i such that 0 <= i <= na-1 and 0 <= i+dx <= nb-1 => rows_overlap = max(0, min(na, nb-dx) - max(0, -dx) )? But the maximum overlapping area occurs when the two matrices are centered? Actually the number of overlapping rows = na + nb - 1 - |dx|? Not exactly. But anyway, our method will compute counts for each dx,dy. Since all ones, count = overlapping area. So the shift that maximizes overlapping area will have maximum count. Our method will find that. Good.
Now consider A and B having ones only in some positions, sometimes overlapping area might be larger but with fewer matches. Our method picks matches.
Now confirm with sample: Already done.
Thus solution correct.
Now we should also consider memory: counts array size <= 100x100 = 10k, trivial.
Thus final answer.
I'll produce final solution code accordingly.
But note: Input reading: after reading na, ma, we read na lines. The lines may be read with newline. Using input().strip() is safe. However, there could be spaces? The problem says each line contains ma characters without spaces. So fine.
Now I'll write final solution in Python.
One more nuance: The indices i and j in loops: We used 0-index. This corresponds to shift as defined: x = row index in B minus row index in A, with 0-index. To verify with 1-index definition: In 1-index, shift (x,y) means A(i,j) aligns with B(i+x, j+y). If we convert to 0-index: A[i0][j0] corresponds to B[i0 + x][j0 + y]. So x = (row_B_1index - 1) - (row_A_1index - 1) = row_B_1index - row_A_1index. So indeed our dx = iB - iA matches the shift as defined. So output is correct.
Now test with a random small case by brute force to ensure method matches naive.
But I think it's fine.
One more check: The problem statement says "Print two space-separated integers x, y (|x|, |y| ≤ 10^9) — a shift with maximum overlap factor." So we must output x and y. We are outputting dx, dy which might be up to about 49, so within bound.
Thus finalize.
Now produce final answer. ```python
import sys
def main():
input = sys.stdin.readline
# read first matrix
na, ma = map(int, input().split())
onesA = []
for i in range(na):
row = input().strip()
for j, ch in enumerate(row):
if ch == '1':
onesA.append((i, j))
# read second matrix
nb, mb = map(int, input().split())
onesB = []
for i in range(nb):
row = input().strip()
for j, ch in enumerate(row):
if ch == '1':
onesB.append((i, j))
# possible shift range: x from -(na-1) to nb-1, y from -(ma-1) to mb-1
offset_x = na - 1
offset_y = ma - 1
size_x = na + nb - 1
size_y = ma + mb - 1
cnt = [[0] * size_y for _ in range(size_x)]
# count matches for every shift that aligns at least one '1'
for iA, jA in onesA:
for iB, jB in onesB:
dx = iB - iA
dy = jB - jA
ix = dx + offset_x
iy = dy + offset_y
cnt[ix][iy] += 1
# find the shift with the highest count
best_val = -1
best_dx = best_dy = 0
for ix in range(size_x):
row = cnt[ix]
for iy in range(size_y):
val = row[iy]
if val > best_val:
best_val = val
best_dx = ix - offset_x
best_dy = iy - offset_y
print(best_dx, best_dy)
if name == "main":
main()