We are given a problem about flipping rows and columns of a binary matrix to maximize the number of zeros (or ones?). Let's carefully understand the problem.
We have a machine that bakes rice crackers. They have a traditional method: front side baked, then turned over, then back side baked. Normally, after baking front side, all crackers are turned over and then baked back side. But an earthquake occurred just before turning over, and some crackers turned over (i.e., flipped) by themselves? Actually: "some rice crackers turned over." The text: "an earthquake occurred just before turning over the rice crackers, and some rice crackers turned over." So initially, before any manual operation, the state after earthquake is given. This state reflects which side is currently facing up? They show a figure: black circles represent front side burnt, white circles back side burnt. They then show flipping first row, then flipping columns 1 and 5, and achieve 9 crackers that can be shipped.
We need to maximize number of crackers that can be shipped. Conditions: The crackers that can be shipped are those that are baked correctly on both sides without overcooking the front side. Let's parse the story to translate into a combinatorial optimization.
Interpretation: The crackers need to be baked on both sides. The traditional method: first bake front side for a set time, then flip all, then bake back side for a set time. After the earthquake, some crackers have flipped spontaneously. The front side had already been baked (maybe not? Actually they were in the process: they had baked the front side and were about to flip, but earthquake caused some to flip). The front side baking time is fixed and if we continue baking front side any more (i.e., if after earthquake we don't flip them and then they get baked on the same side again?) Actually: "if the front side was baked any more, the baking time set by the tradition would be exceeded, and the front side would be overcooked". So we need to avoid further baking on the front side. We can manually flip rows/columns to get crackers into the correct orientation before the back side baking. But the machine can only flip entire rows or columns. We want to maximize the number of crackers that, after we perform some set of row flips and column flips (or maybe no flips), will end up with the correct orientation such that when we then bake the back side (which presumably bakes the side that is currently facing up? Actually we are going to bake the back side after flipping? Wait: after manual flipping, the machine will then continue with the back side baking? The description: "we decided to increase the number of rice crackers that can be baked on both sides without overcooking the front side, that is, the number of 'rice crackers that can be shipped'." So we need to arrange the flipping so that for as many crackers as possible, the side that will be baked in the second bake is the back side, not the front side.
Specifically: There are two sides: front (which is already baked) and back (which needs baking). In the second phase, the machine will bake whatever side is facing up after we do our flips? Or will it always bake the back side? Actually, normally after flipping all, the back side is facing up and is baked. Here we might not flip all; we only flip some rows/columns. The second baking is still going to happen (presumably for the set time) and it will bake whichever side is facing up. If that side is the front side (which already got baked), then it will be overcooked (baked twice) and thus cannot be shipped. So we need to ensure that after our manual flips, the cracker has its back side facing up, so that the second bake bakes the back side, completing both sides. Those crackers become shippable. The ones that end up with front side up will be overbaked.
But what about the crackers that spontaneously flipped during the earthquake? Initially, after the earthquake, each cracker is in some orientation: either it is in its original orientation (front side up) or it has flipped (back side up). The state given: ai,j = 1 means front side burnt (so front side up? Or burnt meaning it's been baked? Actually "front side burnt" means the front side has been baked? The color: black circles represent state where the front side is burnt, white circles represent state where the back side is burnt. So after the initial front-side baking, all crackers should have front side burnt (since they baked front side). However, the earthquake might cause some to flip, so now some have back side up, which is not yet burnt. So the state given (ai,j) indicates which side is currently burnt? Let's decode: They say: "If ai and j are 1, it means that the front side is burnt, and if it is 0, it means that the back side is burnt." But that seems contradictory: both sides can't be burnt unless both are baked. Actually after only first bake, only front side is burnt. Back side is not burnt. So if a cracker is flipped, the back side would be up but not burnt? But the state says "back side is burnt" for 0. That is confusing. Perhaps the state indicates the side that is currently facing up? But they say "burnt". Let's think: After the front side bake, each cracker has front side burnt. Then some flip. Now the side facing up may be either burnt (if front side up) or unburnt (if back side up). But the state given by 1/0 says "front side is burnt" vs "back side is burnt". It could be that they indicate which side is currently up and is burnt? Actually if a cracker flips, the back side is now up, but it hasn't been baked yet, so it's not burnt. So it wouldn't be "back side burnt". So maybe the state describes which side is facing up and will be burnt if we bake now? That seems odd.
Let's look at the examples to infer.
Example 1:
R=2, C=5
State:
0 1 0 1 0
1 0 0 0 1
Interpretation: In the text, they show a figure (not given) but they describe flipping first row and then columns 1 and 5 resulting in 9 shipped.
We need to compute maximum shipped crackers by choosing a set of rows and columns to flip. But what constitutes a shipped cracker after flips? Likely a cracker that after all flips has a certain value (say 0 or 1) that indicates back side up (so that second bake will burn the back side). But which value corresponds to back side up? In the given state, 0 means back side burnt? But after flips, if we flip a row or column, we change orientation of those crackers (i.e., toggle between front/back). That toggles the burnt state? Actually flipping a cracker swaps which side is up. If front side was up (and burnt), after flipping, back side is up (unburnt). So the burnt status changes? The cracker itself: front side burnt, back side not burnt. If we flip, the side that was up changes, but the burnt state of each side remains. So if we represent state by which side is up and its burnt status, it's ambiguous.
Maybe they represent the state as: after earthquake, each cracker is either in correct orientation (front side up, ready to be flipped later) or incorrectly flipped (back side up). But they assign 1 to front side burnt (i.e., the front side has been baked) and 0 to back side burnt (i.e., the back side has been baked)? That can't be because back side hasn't been baked. Unless the earthquake caused some to flip and then the baking continued? No, the story says: after earthquake, they stopped the baking? Actually: "an earthquake occurred just before turning over the rice crackers, and some rice crackers turned over. Fortunately, the condition of the charcoal fire remained appropriate, but if the front side was baked any more, the baking time set by the tradition would be exceeded and the front side would be overcooked... Therefore, I hurriedly changed the machine to manual operation and tried to turn over only the rice crackers that had not been turned inside out." So they were about to flip all (to start the second bake). But some have already flipped due to earthquake. So they now want to flip only the ones that need to be flipped so that after flipping, all (or as many as possible) have back side up, and then they will do the second bake. However, they can only flip entire rows or columns.
Thus, the initial state: each cracker is either correctly oriented (front side up) or incorrectly flipped (back side up) due to earthquake. The 1/0 in the input likely indicates: 1 = front side up (front side burnt, i.e., already baked), 0 = back side up (back side not yet baked). Or maybe reversed. They said: "If ai and j are 1, it means that the front side is burnt, and if it is 0, it means that the back side is burnt." But that phrase might be misinterpretation: perhaps they meant "If ai,j is 1, it means that the front side is burnt (i.e., that side is currently facing up and burnt), and if it is 0, it means that the back side is burnt." However, that would imply that some crackers have back side burnt already, which doesn't fit story. Maybe the earthquake happened after flipping? No, it says "just before turning over the rice crackers". So before the intended mass flip. So no back side is burnt.
Let's look at example to deduce.
Given state for 2x5:
Row1: 0 1 0 1 0
Row2: 1 0 0 0 1
If we interpret 1 = front side up (needs to be flipped to get back side up), 0 = back side up (already flipped, so it's good). Then we want as many as possible after our flips to be back side up (0). But we can flip rows and columns, which toggles each cell's state (if we consider flipping changes orientation: if we flip a row, all cells in that row get flipped (so front becomes back, back becomes front). This is consistent: flipping a cracker toggles whether it's front up or back up. So after performing a set of row flips and column flips, each cell's final orientation is: initial XOR (rowFlip[i] XOR colFlip[j]), because flipping both row and column flips twice (back to original). This is standard.
Now, the objective: maximize number of cells that are back side up (0) after flips. However, is that correct? In the example, they said: "If you turn the first line over, you will see the state shown in the following figure. Furthermore, when the 1st and 5th columns are turned over, the state is as shown in the following figure. In this state, 9 rice crackers can be shipped."
So starting from initial state, they flip row1, then flip columns 1 and 5. Let's compute if we interpret 1 = front up (bad, needs to become 0) and 0 = back up (good, desired).
Initial matrix:
Row1: [0,1,0,1,0]
Row2: [1,0,0,0,1]
Flip row1 (toggle row1): becomes [1,0,1,0,1]
Now matrix:
Row1: 1 0 1 0 1
Row2: 1 0 0 0 1
Then flip columns 1 and 5. Flip col1 toggles both rows at column1: col1 becomes [0,0]? Actually current col1: row1=1, row2=1 -> after flip: row1=0, row2=0. Flip col5 toggles column5: current col5: row1=1, row2=1 -> after flip: row1=0, row2=0.
Result matrix:
Row1: after col1 and col5 flips, row1's columns: col1 becomes 0 (from 1), col5 becomes 0 (from 1), others unchanged: so row1: 0,0,1,0,0? Wait need to recompute properly: After row flip, we had row1: [1,0,1,0,1]; row2: [1,0,0,0,1]. Then flip col1: toggle positions (1,1) and (2,1): row1 col1: 1->0; row2 col1:1->0. Flip col5: toggle (1,5) and (2,5): row1 col5:1->0; row2 col5:1->0. Others unchanged. So final:
Row1: [0,0,1,0,0] -> zeros: 4? Actually values: col1=0, col2=0, col3=1, col4=0, col5=0 => zeros count = 4.
Row2: [0,0,0,0,0] -> zeros count = 5. Total zeros = 9. So 9 crackers become back side up. That matches shipping 9.
Thus maximizing the number of zeros after flips corresponds to maximizing shipped crackers.
Therefore the problem is: Given a binary matrix A of size R x C (R up to 10, C up to 10000), we can choose any subset of rows to flip (i.e., toggle all bits in those rows) and any subset of columns to flip (toggle all bits in those columns). After these flips, we want to maximize the number of zeros in the resulting matrix.
Note: Flipping a row then a column toggles a cell twice if both are flipped, which is equivalent to XOR of row flip and column flip.
Thus final value at (i,j) = A[i][j] XOR r[i] XOR c[j], where r[i] ∈ {0,1} indicates whether row i is flipped, c[j] ∈ {0,1} indicates whether column j is flipped. We want to maximize # of positions where final value = 0.
Equivalently, minimize # of ones, but maximize zeros.
Since R is small (≤10), we can iterate over all 2^R possibilities for row flips. For each fixed row flip pattern r[1..R], we then decide column flips c[j] to maximize zeros.
For each column j, the column's values after row flips become B[i][j] = A[i][j] XOR r[i]. This column has R bits. Then we can choose c[j] (0 or 1). The final value for that column is B[i][j] XOR c[j]. For a given column, the number of zeros after choosing c[j] is:
If c[j] = 0, zeros = count of B[i][j] = 0.
If c[j] = 1, zeros = count of B[i][j] = 1 (since flipping makes ones become zeros).
Thus for column j, the best zeros contributed = max( count0, count1 ), where count0 = number of rows i with B[i][j] = 0, count1 = R - count0 = number with B[i][j] = 1.
So given row flips, we can compute for each column the number of zeros from best column flip. Sum over columns yields total zeros for that row flip pattern. Then we take max over all row flips.
Complexities: O(2^R * R * C) which with R ≤ 10, C ≤ 10000, datasets ≤5, is feasible (2^10=1024, times 1010000 = 100k => about 102 million ops, which is fine in C++/Python? Might be borderline in Python but likely okay with optimization. But note C up to 10000, R up to 10, 2^10=1024, product ~10 million columns processed? Actually 1024 * 10000 = 10.24 million columns, each column we need to count zeros after row flips. If we do per column counting of bits for each row flip pattern separately, we might get O(2^R * R * C) = 102410*10000 = 102.4 million operations, which is okay in Python if coded efficiently (using bit operations?). However, we can do better: precompute for each column its original bits as a bitmask of length R, since R <= 10, we can represent each column as an integer between 0 and 2^R -1. Then for each row flip pattern r (also as mask), we compute B column = original_mask XOR r (since flipping rows toggles bits per row: if r has bit i set, then all bits in that row are flipped. But careful: row flips are applied to rows, so toggling row i toggles all columns in that row. So for a column j, the bits after row flips are: for each i, A[i][j] XOR r[i]. That is exactly original column mask XOR r, because r is applied to each bit; if r[i]=1, then A[i][j] flips. So B_mask = col_mask ^ r. Then count0 = number of zeros in B_mask = R - popcount(B_mask). count1 = popcount(B_mask). Best zeros for column = max( R - popcnt, popcnt ). So we can precompute popcount for all possible masks (0..2^R-1). Then for each row flip pattern r, for each column j, compute B_mask = col_mask[j] ^ r, then look up popcount(B_mask) and compute best = max(pop, R-pop). Sum over j.
So algorithm:
- Read R, C.
- For each column j, build an integer mask: for i in 0..R-1, set bit i if A[i][j] == 1. (Rows given as R lines, each with C ints).
- Precompute popcount for all masks from 0 to (1<<R)-1.
- For each r in 0..(1<<R)-1:
total = 0
For each column mask m in col_masks:
flipped = m ^ r
ones = pop[flipped]
zeros = R - ones
total += max(ones, zeros)
ans = max(ans, total)
Edge cases: None.
But is the interpretation of shipped crackers being zeros correct? In the example, we got 9 zeros after flips. They said 9 crackers can be shipped. That matches. So answer = total zeros.
Now note: The problem states: "Consider the case where no horizontal rows are flipped, or no vertical columns are flipped." That might be an instruction: we can choose to flip no rows, or no columns, but obviously we can also flip both. Actually it says: "Write a program that outputs the maximum number of rice crackers that can be shipped." So we are to output maximum.
Thus solution seems straightforward.
But wait, there's a nuance: The flips are performed in sequence? Does flipping rows then columns yield same as columns then rows? Since flips are commutative and each flip toggles entire row/col, the final state depends only on which rows and columns are flipped, not order. So we are fine.
But is there any restriction that we cannot flip both a row and a column? No.
Thus we just need to compute as above.
However, there might be another interpretation: Some crackers might already have both sides burnt? Not in story. So our interpretation stands.
Double-check with second example:
Input:
3 6
1 0 0 0 1 0
1 1 1 0 1 0
1 0 1 1 0 1
0 0
Output 15.
Let's test manually with our algorithm.
R=3, C=6.
Matrix:
Row0: [1,0,0,0,1,0]
Row1: [1,1,1,0,1,0]
Row2: [1,0,1,1,0,1]
Compute column masks:
col0: bits: row0=1, row1=1, row2=1 => mask = 111b = 7
col1: 0,1,0 => 010b = 2
col2: 0,1,1 => 011b = 3
col3: 0,0,1 => 001b = 1
col4: 1,1,0 => 110b = 6
col5: 0,0,1 => 001b = 1
Now iterate over row flips r from 0 to 7. For each r compute sum of max(pop(m^r), 3-pop). Let's compute quickly.
Prepop: popcount for 0..7: 0,1,1,2,1,2,2,3.
We want max zeros per column.
We can compute manually maybe find max = 15.
Total cells = 3*6 = 18. So answer 15 means we can have 15 zeros, i.e., only 3 ones remain. That seems plausible.
Let's test r=0: For each m:
- m=7 -> m^0=7 pop=3 -> zeros=0 -> max=3? Actually ones=3, zeros=0 => max = max(3,0)=3 (ones become zeros if we flip? Wait careful: best zeros = max( count0, count1 ). For m=7 pop=3 => count1=3, count0=0 => best zeros = max(0,3) = 3. That means by flipping column (c[j]=1) we can turn all three ones to zeros, achieving 3 zeros. So best zeros from column is 3.
- m=2 -> pop(2)=1 => count1=1, count0=2 => best zeros = max(2,1)=2.
- m=3 -> pop=2 => best zeros = max(1,2)=2? Wait count0 = 3-2=1, count1=2 -> max(1,2)=2.
- m=1 -> pop=1 => count0=2, count1=1 -> max=2.
- m=6 -> pop=2 => count0=1, count1=2 -> max=2.
- m=1 -> same as above =>2.
Sum = 3+2+2+2+2+2 = 13.
So with no row flips, max zeros = 13.
Now try r=1 (binary 001). Then:
m=7: 7^1=6 pop=2 => count1=2, count0=1 => max=2? Actually max zeros = max(count0, count1) = max(1,2)=2.
m=2: 2^1=3 pop=2 -> max = max(1,2)=2.
m=3: 3^1=2 pop=1 -> max = max(2,1)=2.
m=1: 1^1=0 pop=0 -> max = max(3,0)=3.
m=6: 6^1=7 pop=3 -> max = max(0,3)=3.
m=1: same as m=1 ->3.
Sum=2+2+2+3+3+3 = 15. That's 15. So maximum is 15.
Thus matches output.
So problem solved.
Now the input format: Multiple datasets, terminated by line "0 0". R and C up to 10 and 10000 respectively. Number of datasets ≤5.
Implementation details:
We'll read lines. For each dataset, read R, C. If both zero, break. Then for i in range(R): read list of C ints. We'll compute col_masks as list of ints length C.
For each column j, build mask: iterate rows i from 0 to R-1: if A[i][j] == 1, set bit i. Since rows are given per row, we can process while reading: for each row i, read C values; for each j, if value is 1, set bit i in col_masks[j]. Initially col_masks = [0]*C.
Alternatively, after reading entire matrix into a list of lists, we can compute col masks.
But note memory: C up to 10000, storing matrix of ints (RC) is at most 1010000 = 100k entries, fine.
But we can also compute col masks on the fly to save memory: read first row, initialize col_masks with those bits (maybe shift). However, R is small, we can store.
After building col_masks, precompute popcount for all masks up to (1<<R)-1. Use built-in bit_count in Python 3.8+? In Python 3.10+, int.bit_count() is available. Use that for each mask or compute array.
Since we have at most 1024 masks, we can compute pop = [bin(m).count('1') for m in range(1<<R)] or use bit_count.
Then iterate r from 0 to (1<<R)-1:
total = 0
for m in col_masks:
flipped = m ^ r
ones = pop[flipped]
zeros = R - ones
total += max(ones, zeros)
ans = max(ans, total)
Print ans.
Potential optimization: Since col_masks may have many duplicates, we can count frequencies of each mask to reduce inner loop from C to up to 2^R distinct masks. With C up to 10000 and R ≤10, number of distinct masks at most 1024. So we can compute a frequency dict: for each column mask, count occurrences. Then inner loop iterates over distinct masks and multiplies by count. This can speed up especially if C large but still fine. But not necessary; 10 million iterations is fine in Python (~0.1 sec? Actually 10 million loops might be 0.2-0.5 sec, but with 5 datasets maybe 2.5 sec, still okay. But careful: 2^R * C = up to 1024 * 10000 = 10.24 million per dataset. For 5 datasets ~51 million. In Python, that loop might be around 1-2 seconds if optimized. Using list and simple operations, it's okay. However, we need to consider overhead of Python loops; using frequency dict reduces inner loop to at most 1024 distinct masks per row pattern, so inner loop size = number of distinct masks (≤1024) instead of C (10000). Then total operations: for each r (1024) we loop over up to 1024 masks, so ~1 million per dataset. That is even better. So we can implement frequency for speed.
Implementation with frequency:
from collections import Counter
col_masks_list = [mask for each column]
freq = Counter(col_masks_list)
Then for each r:
total = 0
for mask, count in freq.items():
flipped = mask ^ r
ones = pop[flipped]
zeros = R - ones
total += count * max(ones, zeros)
ans = max(ans, total)
That is efficient.
Edge Cases: R=1. Then masks are either 0 or 1. pop[0]=0, pop[1]=1. For each column, best zeros = max(pop, 1-pop) = max(0,1)=1 if flipped? Actually if R=1, then for each column we can always achieve zero by appropriate column flip? Let's test: If mask=0, then r can be 0 or 1. For a given r, flipped = mask ^ r = r. ones = pop(r). zeros = 1-ones. max(ones, zeros) = max(pop(r), 1-pop(r)). For r=0, ones=0, zeros=1 -> max=1. For r=1, ones=1, zeros=0 -> max=1. So each column always contributes 1 zero regardless of row flip? But row flips may affect because we may choose column flip optimally per column. Actually with R=1, we have only one row. Flipping rows just toggles that entire row. But then per column we can flip column independently to get zero. Indeed each column can be made zero by appropriate column flip irrespective of row flip? Let's see: Initial bit a. After row flip r, the bit becomes a^r. Then we can flip column c: final = a^r^c. We can choose c to make final 0: c = a^r. So we can always get zero. So answer = C. That matches our formula: for any r, each column yields max=1, total C. So answer = C. Good.
When R is larger, same logic: each column can be made at least floor(R/2) zeros? Actually best = max(ones, zeros) so at least ceil(R/2). But with row flips we can sometimes get more zeros per column.
Now verify that flipping both row and column can be done arbitrarily? Yes.
Thus problem solved.
Now just implement.
We should read input until "0 0". Input example shows "0 0" on last line. The datasets numbers ≤5.
Implementation steps:
while True:
line = input().strip()
while line == "" : skip? But probably no empty lines.
R, C = map(int, line.split())
if R==0 and C==0: break
col_masks = [0]*C
for i in range(R):
row = list(map(int, input().split()))
for j in range(C):
if row[j] == 1:
col_masks[j] |= (1 << i) # set bit i
freq = Counter(col_masks)
maxR = 1 << R
pop = [0]*maxR
for m in range(maxR):
pop[m] = m.bit_count() # Python 3.8+? Actually int.bit_count introduced in Python 3.8? Yes, 3.8+ . Use bin(m).count('1') if not.
ans = 0
for r in range(maxR):
total = 0
for mask, cnt in freq.items():
flipped = mask ^ r
ones = pop[flipped]
zeros = R - ones
total += cnt * max(ones, zeros)
if total > ans:
ans = total
print(ans)
We must ensure that when R is up to 10, maxR=1024, fine.
Now double-check example:
First dataset: R=2, C=5, masks? Row0: [0,1,0,1,0]; Row1: [1,0,0,0,1]
col0: row0=0, row1=1 => mask = (row1 bit) so bit0? We set bits: bit i corresponds to row index. Usually we use i from 0 to R-1. Let's define: For i row (0-index), set bit i if A[i][j]==1. So row0 = bit0, row1 = bit1. Then col0: row0=0, row1=1 => mask = 1<<1 = 2? Actually bit1 is set, so mask = 2 (binary 10). col1: row0=1, row1=0 => mask = 1<<0 =1. col2: row0=0, row1=0 => 0. col3: row0=1, row1=0 =>1. col4: row0=0, row1=1 =>2. So masks: [2,1,0,1,2]. R=2, maxR=4. pop[0]=0,pop[1]=1,pop[2]=1,pop[3]=2.
Now iterate r (0..3). We'll compute total zeros for each r using our method. r=0:
For each mask:
mask=2 -> flipped=2 pop=1 -> ones=1 zeros=1 -> max=1? Actually max(1,1)=1? Wait R=2 so count0=1, count1=1 => best zeros = max(1,1)=1. But earlier we got for column with mask 2 (col0) best zeros =? With r=0, after row flips (none), column values: row0=0, row1=1. Then we can flip column to get either 0,1 -> zeros: if no column flip, zeros=1 (row0=0); if flip, zeros=1 (row1 becomes 0). So max zeros =1. That matches. So each column contributes 1? Wait earlier we computed final zeros total =9. With r=0, we had 13 zeros? Actually earlier we computed for first example with r=0 (no row flips) and column flips optimally: we got 9? Let's recompute: initial matrix 2x5. For each column we can flip column to maximize zeros. Column wise:
col0: [0,1] -> zeros without flip=1 (first row 0); with flip-> [1,0] zeros=1; best=1.
col1: [1,0] -> zeros without flip=1; with flip-> [0,1] zeros=1; best=1.
col2: [0,0] -> zeros without flip=2; with flip->[1,1] zeros=0; best=2.
col3: [1,0] -> best=1.
col4: [0,1] -> best=1.
Total = 1+1+2+1+1=6. But earlier we got total zeros 9 after row and column flips (r=1, col flips 1 and 5). That total is 9. So with r=0, best total zeros = 6. Our method says for r=0, total = sum of max per column =? Using masks: col0 mask=2 -> max=1; col1 mask=1 -> max=1; col2 mask=0 -> max = max(pop(0)=0 -> zeros=2, so max zeros = max(0,2)=2; col3 mask=1 ->1; col4 mask=2 ->1; sum=6. So correct.
Now for r=1 (binary 01) i.e., flip row0? Wait r bits: bit0 corresponds to row0, bit1 to row1? r=1 means flip row0 only. So r=1. Then:
For each mask, flipped = mask ^ 1.
- mask=2 (10) ^ 01 = 11 (3) pop=2 -> ones=2, zeros=0 -> max = max(0,2)=2.
- mask=1 (01) ^ 01 = 0 pop=0 -> max = max(2,0)=2.
- mask=0 ^1 =1 pop=1 -> max = max(1,1)=1? Actually zeros=1, ones=1, max=1.
- mask=1 -> same as col1: becomes 0 -> 2
- mask=2 -> becomes 3 -> 2
Sum = 2+2+1+2+2 = 9. Yes, matches. So algorithm yields max 9. Good.
Thus final answer.
Now we should confirm that the problem statement's phrase "Consider the case where no horizontal rows are flipped, or no vertical columns are flipped." might be just indicating that it's allowed to flip none. But we are already covering that.
Thus code as described.
Now about reading input: The input might have extra spaces, lines. Use sys.stdin.read().split() for speed and simplicity.
We can parse all integers.
Pseudo:
import sys
from collections import Counter
def main():
data = sys.stdin.read().strip().split()
it = iter(data)
out_lines = []
while True:
try:
R = int(next(it))
C = int(next(it))
except StopIteration:
break
if R == 0 and C == 0:
break
# initialize col_masks
col_masks = [0]*C
for i in range(R):
for j in range(C):
val = int(next(it))
if val == 1:
col_masks[j] |= (1 << i)
freq = Counter(col_masks)
maxR = 1 << R
pop = [0]*maxR
for m in range(maxR):
pop[m] = m.bit_count()
ans = 0
for r in range(maxR):
total = 0
for mask, cnt in freq.items():
flipped = mask ^ r
ones = pop[flipped]
zeros = R - ones
total += cnt * max(ones, zeros)
if total > ans:
ans = total
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
Check compatibility with Python version: bit_count is Python 3.8+. We can also use bin(m).count('1').
But note: In Python 3.10, bit_count is available. In online judges, they often use Python 3.8+, so fine. If not, we can define pop = [bin(m).count('1') for m in range(maxR)], which is also fine for maxR=1024.
Now test on sample input:
Input:
2 5
0 1 0 1 0
1 0 0 0 1
3 6
1 0 0 0 1 0
1 1 1 0 1 0
1 0 1 1 0 1
0 0
Our code should output:
9
15
Yes.
Edge Cases: R=10, C=10000, 5 datasets. Complexity: For each dataset: building masks O(R*C) ~ 100k, freq building O(C) ~ 10k, then 2^R * distinct masks ≤ 1024 * 1024 = ~1M operations, each simple arithmetic, fine.
Now verify that we considered the case where no flips allowed? Actually all subsets allowed.
Now output: one line per dataset.
Thus answer.
I'll produce final answer. ```python
import sys
from collections import Counter
def main():
data = sys.stdin.read().strip().split()
it = iter(data)
out = []
while True:
try:
R = int(next(it))
C = int(next(it))
except StopIteration:
break
if R == 0 and C == 0:
break
# Build column masks: mask[j] has bit i set if A[i][j] == 1
col_masks = [0] * C
for i in range(R):
for j in range(C):
if int(next(it)) == 1:
col_masks[j] |= (1 << i)
# Count frequencies of identical column masks
freq = Counter(col_masks)
# Precompute popcount for all masks up to 2^R
max_mask = 1 << R
pop = [0] * max_mask
for m in range(max_mask):
pop[m] = m.bit_count() # Python 3.8+; else use bin(m).count('1')
best_total = 0
# Try all row flip patterns
for r in range(max_mask):
total = 0
for mask, cnt in freq.items():
flipped = mask ^ r
ones = pop[flipped]
zeros = R - ones
total += cnt * max(ones, zeros)
if total > best_total:
best_total = total
out.append(str(best_total))
sys.stdout.write("\n".join(out))
if name == "main":
main()