You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met.
Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 × 2 does not have any 2-compression:
01 10
For the given matrix A, find maximum x such that an x-compression of this matrix is possible.
Note that the
input is given in compressed form. But even though it is compressed, you'd better use fast input.
Input
The first line contains one number n (4 ≤ n ≤ 5200) — the number of rows and columns in the matrix A. It is guaranteed that n is divisible by 4.
Then the representation of matrix follows. Each of n next lines contains n/4 one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.
Elements are not separated by whitespaces.
Output
Print one number: maximum x such that an x-compression of the given matrix is possible.
We need to find the maximum factor x (dividing n) such that the matrix A can be compressed to size (n/x) by (n/x) where each block of size x x is uniform (all entries equal). So A[i][j] must equal B[ceil(i/x)][ceil(j/x)], which means that within each block of size x x, all entries are identical (all 0 or all 1). Since B entries can be 0 or 1 independently per block, the condition is: for any i1, i2 in the same block row (i.e., ceil(i1/x) = ceil(i2/x)) and j1, j2 in same block column, we must have A[i1][j1] = A[i2][j2] if also they are in the same block? Actually condition says: A[i][j] = B[ceil(i/x)][ceil(j/x)]. So for any i, j within the same block (i.e., ceil(i/x) = I, ceil(j/x) = J), A[i][j] is forced to be equal to B[I][J]. That means all entries in that block must be equal (since B[I][J] is constant for that block). So condition: For each block (I,J) of size x x, all entries A[i][j] for i in ((I-1)x+1 ... Ix) and j in ((J-1)x+1 ... Jx) are the same (either all 0 or all 1). That's the requirement.
Thus we need largest x dividing n such that the matrix is composed of uniform blocks of size x.
Given n up to 5200, but n divisible by 4. Input is compressed: each line has n/4 hex digits, each representing 4 bits. So total entries n*n, with n up to 5200, that's about 27 million bits, which is manageable if we store as bitset? But we need to check uniformity of blocks for many candidate x. We need to find the maximum divisor x. Brute force checking each divisor from large to small and checking condition could be okay if we can check efficiently. Number of divisors of n up to around maybe ~100 (since n max 5200, max divisors not huge). Actually 5040 has many divisors, but n max 5200, so divisors maybe up to ~100. So we can test each candidate x descending.
But we need to check whether all blocks of size x are uniform. Naively checking each block would be O((n/x)^2 * x^2) = O(n^2) per candidate, which for n=5200 and maybe 100 candidates would be 100 * 27M = 2.7B operations, possibly okay in C++ with bit operations? But we need to be careful about time and memory. Also we need to parse the input quickly.
Alternatively, we can precompute something like prefix sums to allow fast check of whether a block is all 0s or all 1s. But we need to check both: either all 0s or all 1s. For a block, we can compute sum of entries; if sum = 0 then all 0; if sum = xx then all 1; otherwise not uniform. So using 2D prefix sums of bits (0/1) we can compute block sum in O(1). So we can precompute prefix sum array of size (n+1)(n+1). Since n up to 5200, that's about 27M integers if we store int? Actually (5201)^2 ≈ 27 million, each int 4 bytes => ~108 MB, which might be okay but memory limit unknown. Usually Codeforces limits 256 MB, so 108 MB is okay. But we could also use bitset plus quick checks. But prefix sums is straightforward.
However note that n is divisible by 4, but n up to 5200, which is small enough for int array. Use vector<vector> ps(n+1, vector(n+1)). We'll fill with bits. We'll parse hex digits to bits.
But we need to be careful with input format: each of n lines contains n/4 one-digit hexadecimal numbers. "Elements are not separated by whitespaces." So each line is a string of length n/4 (since each hex digit represents 4 bits, and total bits per row is n). So we can read each line as string s of length n/4. For each character, convert to its 4-bit binary representation. We'll fill row i (1-indexed) with bits: for j from 0 to n/4-1, char c = s[j]; int val = hex_to_int(c); then for k in 0..3, bit = (val >> (3-k)) & 1? Actually order: "Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row." The phrase "next 4 elements" suggests that the bits are placed in order from most significant to least significant? Usually hex digit B (1011) means the four elements are 1,0,1,1 in that order? Example: they gave: if number B, then corresponding elements are 1011; if number 5 -> 0101. So yes, the binary representation of the hex digit, from most significant bit to least, gives the 4 entries. So for each hex digit, we output bits from high to low.
Thus we can fill array A (size n x n) or directly compute prefix sums as we go.
Approach:
Read n.
Allocate ps (n+1) x (n+1) integer array (maybe using vector of vectors, but could be heavy for 5200x5200 ints -> 108 million ints, 432 MB if 4 bytes each? Wait: 5201*5201 = 27,048,401 entries. Each int 4 bytes -> ~108 MB. Actually 27 million * 4 = 108 MB. That's okay if memory limit is 256 MB. But vector<vector> overhead: each inner vector has its own small overhead, but total overhead maybe n * sizeof(vector) = 5200 * ~24 = ~124KB, negligible. So 108 MB plus A storage maybe if we also store A (bits). But we can avoid storing A separately by directly updating prefix sums row by row as we parse. But prefix sum array itself needs to be built. We could compute ps iteratively: ps[i][j] = ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1] + a[i][j]. So we need a[i][j] for current row. We can parse row and store temporarily in a row array (size n) of bits (maybe bool) to compute ps row. But we could compute on the fly: after parsing the row into an array of bits, we can compute ps[i][j] using previous ps. That still requires storing the row only, not full A. So total memory: ps (int) 108 MB, plus row (bool) ~5KB, that's fine.
But careful: int may be 4 bytes, but 108 MB is okay but might be borderline if memory limit is 128 MB? Usually Codeforces memory limit for such problems is 256 MB, but I've seen 256 MB typical. However we can reduce memory by using unsigned short if n <= 5200 and sum could be up to n*n = 27e6, which fits in 32-bit int, but short (16-bit) max 65535, not enough. Could use 32-bit. Could also use vector<vector> but then we risk overflow. We'll use int.
Alternatively we can compute prefix sums using bitset and block sums? But prefix sum is simple.
Check time: building ps O(n^2) ~ 27M operations, each adding ints, fine. Then for each divisor x, we need to check O((n/x)^2) blocks, each O(1) using prefix sums. Summing over all divisors, total checks maybe sum_{x|n} (n/x)^2. Since n=5200, worst-case many divisors: e.g., n=5040, divisors: many. Let's estimate sum_{d|n} (n/d)^2 = n^2 * sum_{d|n} 1/d^2. Since d >= 1, sum_{d|n} 1/d^2 <= sum_{d=1..n} 1/d^2 ≈ π^2/6 ~ 1.6449. So total checks <= 1.6449 * n^2 ≈ 1.64 * 27e6 = 44M. Actually n^2 = 27e6, times 1.64 = 44M. So total number of block checks across all divisors is at most ~44 million, each O(1) with few operations, very manageable. So we can just test all divisors in descending order, break when find one that works.
Thus overall algorithm:
Parse input, build 2D prefix sum array ps where ps[i][j] = sum of A[1..i][1..j] (1-indexed).
Compute list of divisors of n (values of x such that x divides n). Sort descending.
For each x in divisors:
Let blocks = n / x.
For each block row I from 1 to blocks:
For each block col J from 1 to blocks:
Compute sum of block:
i1 = (I-1)x, j1 = (J-1)x (since ps indices start 0 at 0). Actually careful: if ps is defined with ps[0][]=0, ps[][0]=0, then block rows: rows from (I-1)x+1 to Ix. So we can compute:
r1 = (I-1)x, c1 = (J-1)x
r2 = Ix, c2 = Jx
sum = ps[r2][c2] - ps[r1][c2] - ps[r2][c1] + ps[r1][c1]
If sum != 0 and sum != x*x, then block not uniform -> fail.
If all blocks uniform, then x works; output x and return.
If none fail, x works.
Since x=1 always works (each cell is its own block, sum=1 or 0, always uniform), answer at least 1.
Edge Cases: Check if x=n: then block size n, only one block. Condition is entire matrix uniform (all 0 or all 1). So we can test that.
Now the parsing: We'll read n, then loop i from 1 to n:
read a string s of length n/4 (since no spaces). There may be whitespace? Input lines: each line contains n/4 one-digit hexadecimal numbers (without whitespaces). So it's a string of length n/4. Possibly there could be newline etc. So we can read using cin >> string (but careful: if lines may have spaces? No). Use fast IO: ios_base::sync_with_stdio(false); cin.tie(0); etc.
For each character c in s:
Convert hex digit to integer: if '0'-'9': val = c - '0'; else if 'A'-'F': val = 10 + (c - 'A').
Then for k in 0..3:
bit = (val >> (3 - k)) & 1.
col = j*4 + k + 1.
We'll fill a row array col index. But we need to compute prefix sums incrementally. We can fill a row array of ints (0/1) for columns 1..n. Then after finishing row, we can update ps[i][j] = ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1] + row[j]. However we could compute ps on the fly without storing full row: we can update ps as we parse each bit? But ps is 2D, need previous row's ps values. We could keep an array prev_ps (size n+1) for previous row's ps values to compute current row's ps without storing the whole ps? Actually we need full 2D ps for later queries. So we need to store entire ps. But we can compute ps row by row: after we have the current row's values row[1..n], we can compute the current row of ps: for j from 1 to n: ps[i][j] = ps[i-1][j] + row_prefix_sum[j] where row_prefix_sum[j] is cumulative sum in current row? More efficiently: maintain running sum in current row: cur_sum = 0; for j from 1 to n: cur_sum += row[j]; ps[i][j] = ps[i-1][j] + cur_sum. This uses O(1) extra memory per row besides ps. So we don't need to store row array; we can process each bit and accumulate cur_sum and directly set ps[i][j] using previous row's ps. Implementation: after reading each hex digit and expanding bits, for each bit we have column index col. We maintain cur_sum (cumulative sum of bits in this row so far). Then ps[i][col] = ps[i-1][col] + cur_sum. But careful: ps[i-1][col] is known from previous row; we need to have ps as a 2D array. However we are filling ps row i across columns, but we need ps[i-1][col] for each col. That's fine; we have the whole ps array from previous rows. So we can do:
for i from 1 to n:
cur_sum = 0;
read string s;
col = 1;
for each char c in s:
val = hex2int(c);
for shift in 3..0:
bit = (val >> shift) & 1;
cur_sum += bit;
ps[i][col] = ps[i-1][col] + cur_sum; // note: we are using ps[i-1][col] which is cumulative sum up to previous row and this column.
col++;
// after loop, col should be n+1? Actually we have exactly n bits.
But careful: The prefix sum formula ps[i][j] = sum_{r=1..i} sum_{c=1..j} A[r][c]. The recurrence: ps[i][j] = ps[i-1][j] + (prefix sum in row i up to j). So if we maintain cur_sum as sum_{c=1..j} A[i][c], then indeed ps[i][j] = ps[i-1][j] + cur_sum. So this works.
Thus we don't need row array; we just compute ps as we parse. But we must ensure that ps[i-1][col] is already computed. Since we compute rows sequentially, yes.
Memory: ps as 2D array of size (n+1)(n+1) ints. n up to 5200 => 52015201 ≈ 27M ints. At 4 bytes each => 108 MB. Acceptable.
But we need to allocate this in C++. Using vector<vector> of size (n+1) each row vector of size (n+1) ints. That's 27M ints. However, each inner vector is allocated separately, which might cause memory fragmentation and overhead. But overhead per vector is small (like pointer, size, capacity). Typically 24 bytes per vector, times 5201 => ~125 KB overhead, negligible. The bigger issue is that vector<vector> stores pointers to rows; it's fine.
But we must ensure we don't exceed memory. 108 MB + overhead < 128 MB maybe? 108 MB + maybe 0.1 MB = 108.1 MB. That's fine for 256 MB limit. But if limit is 128 MB, it might be borderline but still okay? Actually 108 MB is less than 128 MB. So it should be fine. However, we also have some other minor allocations, but overall < 128 MB. Some judges might have 256 MB, so it's safe.
Alternatively we could use a single flat vector of size (n+1)*(n+1) to reduce overhead. But vector<vector> is fine.
But we need to consider that int may be 4 bytes; on some platforms it's 4. Good.
Now, after building ps, we compute divisors. Since n divisible by 4, but we want all x such that x|n. We'll generate divisors by iterating d from 1 to n, if n % d == 0, push d. Then sort descending. Alternatively, we can iterate from n down to 1 and check divisibility; but that would be O(n * (n/x)^2) which is O(n^3) for n=5200? Actually if we iterate x from n down to 1 and test each, we test many x (like up to 5200). For each x we do O((n/x)^2) checks, total sum_{x=1}^{n} (n/x)^2 = n^2 * sum_{x=1}^{n} 1/x^2 ≈ n^2 * π^2/6 ≈ 1.64 n^2 = 44M. That's still okay! Because even if we test all x from 1 to n (not just divisors), we still have about 44M checks. But wait, we need to test only x that divide n? Actually x must divide n for block compression to be possible because n/x must be integer. The problem says "x divides n" is necessary. So we only need to consider divisors. However if we test all x, we would be checking many x that don't divide n, and we would need to have blocks exactly? For x that doesn't divide n, compression is not possible by definition. So we should only consider divisors. But testing all x from n down to 1 and skipping non-divisors would be many more iterations (5200) but the total number of block checks is only for divisors; we would still need to loop over x=1..n and check if divisor; but the main cost is inside the divisor test. For non-divisors we skip quickly. So total work would be similar. But we can just compute divisors list.
Better to generate divisors: for i from 1 to sqrt(n), if n%i==0: add i and n/i. Then sort descending.
Now, for each x, we need to check blocks. But note: We must be careful about the indices. We'll use 1-indexed ps. So ps[i][j] includes rows 1..i and cols 1..j. Then block rows: I from 1 to blocks. The block rows indices in the matrix: rows from (I-1)x+1 to Ix inclusive. So define r1 = (I-1)x, r2 = Ix. Similarly for columns. Then sum = ps[r2][c2] - ps[r1][c2] - ps[r2][c1] + ps[r1][c1].
Now check if sum == 0 or sum == x*x.
If any block fails, break and try next x.
Potential optimization: Since we are checking divisors descending, and the largest x might be n (if all cells same). That's one block. So we can start with largest divisor.
Edge Cases: n=4? The input sample shows n=4. Works.
Now, we need to ensure we parse hex correctly. Each line string length should be n/4. But note: It might be that there are spaces or newline issues. Use getline or cin. Since we use fast IO and cin >> string, it will skip whitespaces and read the next token. The lines contain only hexadecimal digits (no spaces), so cin >> s will read exactly n/4 characters? Actually cin >> string reads until whitespace, but if the line has no whitespace, it will read the entire line (which is of length n/4). That's fine. But we must be careful that after reading n, there is a newline. cin >> n will leave newline; then cin >> s will read the first row string correctly. However, if any lines might have trailing spaces, not typical. We'll assume no spaces.
But note: The problem statement says: "Elements are not separated by whitespaces." So each line is a continuous string of hex digits.
But wait: The input format says: "Then the representation of matrix follows. Each of n next lines contains n/4 one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F)." It doesn't say there are spaces. So we can read strings of length n/4.
One more nuance: The sample input:
8
E7
E7
E7
00
00
E7
E7
E7
Here n=8, n/4=2, each line has length 2, as expected.
Second example:
4
7
F
F
F
Here n=4, n/4=1, each line length 1, ok.
So reading strings works.
Potential pitfalls: For n divisible by 4, but if n is large, the input lines could be long: n/4 up to 1300 characters (since n=5200). That's fine.
Now, we need to ensure we handle large input quickly. Using cin with string might be fine with ios_base sync off. But we could also use getline. Let's use cin >> for each row string.
Now, for each character, we need to convert to integer. We'll define a function:
int hexVal(char c) {
if (c >= '0' && c <= '9') return c - '0';
else return c - 'A' + 10;
}
But ensure c is uppercase; they say uppercase Latin letters.
Now, for each hex digit, we have 4 bits. We need to process bits in order from most significant to least. So for each hex digit val (0..15), we do for shift = 3 down to 0: bit = (val >> shift) & 1.
Now compute cur_sum and ps.
Implementation details:
We allocate ps as vector<vector>(n+1, vector(n+1, 0)). But 27M ints might take time to allocate and zero-initialize. Zero-initialization of a 2D vector of that size will set all to zero, which is O(n^2) anyway, which is 27M operations, fine.
But maybe we can allocate as a single vector to reduce overhead and improve cache performance. However it's okay.
Alternatively, we could use vector ps((n+1)(n+1)) and index as i(n+1)+j. That would be more cache-friendly and possibly faster. But vector of vectors is easier. However, 27M ints is big; using nested vectors may cause many cache misses due to double indirection. But it may still be okay given the time limits? Usually Codeforces problems with n=5200, O(n^2) solutions with 2D arrays are accepted if optimized. But we need to be careful with performance: building prefix sum with nested loops over i and j, using row-major order, is fine with a single contiguous array. With vector of vectors, each inner vector is contiguous, but they are separate allocations, causing possible overhead in accessing but still fine if we iterate row by row.
However, note that in our parsing method we need to access ps[i-1][col] while computing ps[i][col]. That's random access? Actually we compute columns sequentially for each row, so for each col we read ps[i-1][col] which is from the previous row. That's okay; we are accessing the previous row's same column. If both rows are stored separately, it's fine.
But if we use a flat array, we can compute more efficiently.
Let's decide: use flat vector ps of size (n+1)(n+1). Index mapping: idx(i, j) = i(n+1) + j, where i ranges from 0 to n, j from 0 to n. We'll allocate vector ps((n+1)(n+1), 0). Then to compute cur row i, we need to reference element at (i-1, col). We'll compute offset for current row: base = i(n+1); prev_base = (i-1)*(n+1). Then for col from 1 to n: cur_sum += bit; ps[base + col] = ps[prev_base + col] + cur_sum.
That is efficient.
Now, after building ps, we generate divisors list.
Then for each x (descending), we check blocks.
We need to compute block sums quickly. Using the flat ps, we need to compute:
int r1 = (I-1)x;
int r2 = Ix;
int c1 = (J-1)x;
int c2 = Jx;
int sum = ps[r2*(n+1) + c2] - ps[r1*(n+1) + c2] - ps[r2*(n+1) + c1] + ps[r1*(n+1) + c1];
Note: ps indices are int; we need to ensure we don't overflow. n+1 up to 5201, indices up to 5201*5201 ≈ 27M, within int.
Now, check if sum == 0 or sum == x*x. If not, break.
We can break early from loops when fail.
Complexities: O(n^2) to build ps + O(n^2 * sum_{d|n} 1/d^2) to check. Should be fast.
Now, we need to handle potential large x (like x=n). Then blocks=1. Then we compute sum = ps[n][n] - ps[0][n] - ps[n][0] + ps[0][0] = ps[n][n]. That's total sum. Check if it equals 0 or n*n. Good.
Now, we must ensure that we handle the case where all blocks uniform, but some blocks are all 0, some all 1. That's allowed because B can be 0 or 1 per block arbitrarily. So we just need each block to be uniform (all same). So check sum == 0 or sum == x*x, not that all blocks have same sum.
Now, we should also consider that x must be at least 1, always works.
Now, verify with examples:
Example 1: n=8, matrix given. The output is 1. Our algorithm should find that x>1 fails.
Example 2: n=4, matrix: rows: 7 (0111?), actually hex 7 -> binary 0111? Wait 7 decimal is 7 hex? Actually hex digit '7' is 7 decimal, binary 0111. But they said: 4 rows: 7, F, F, F. So row1: 0111, row2: 1111, row3: 1111, row4: 1111. The matrix:
Row1: 0 1 1 1? Actually 7 hex = 0111 binary, but note order: bits from MSB to LSB: 0,1,1,1. So row1: 0 1 1 1.
Row2: F -> 1111.
Row3: 1111.
Row4: 1111.
So it's not uniform for larger blocks; x=2? blocks 2x2: Block (1,1): rows1-2, cols1-2: row1 col1=0, col2=1; row2 col1=1, col2=1 => not uniform. So answer 1. Works.
Now, consider cases where answer is >1. For example, matrix all zeros: answer = n. Our algorithm will test largest divisor n first: block sum = total sum = 0 -> uniform, so returns n.
Now, consider matrix like checkerboard pattern of size 2? But condition: x must divide n. For a 2x2 matrix with pattern [[0,1],[1,0]]: x=2? block sum=2? Actually total sum = 2, not 0 nor 4, so fails. x=1 works. So answer 1.
Now, we need to ensure we don't overflow int for sum: x*x could be up to n^2 = 27e6, which fits in int (2^31-1). ps entries up to n^2 = 27e6, also fits int.
Now, memory: vector ps((n+1)(n+1)) with (52015201) = 27,048,401 ints. That's about 108 MB. That's okay. But we also need other variables, still within 256 MB. However, some judges may have 64 MB limit? But problem is from Codeforces (likely), memory limit typically 256 MB. In Codeforces, memory limit for this problem is probably 256 MB. I recall similar problems with n up to 5200 using 2D prefix sums with int array of size 5200+1 had memory ~200 MB? Let's compute precisely: n max 5200, so n+1=5201, (5201)^2 = 27,048,401. Times 4 bytes = 108,193,604 bytes ≈ 103 MB? Actually 27,048,401 * 4 = 108,193,604 bytes ≈ 103.2 MB? Wait 27 million * 4 = 108 million bytes = 103 MB? No, 108 million bytes = 108 MB? 1 MB = 2^20 = 1,048,576 bytes. So 108,193,604 / 1,048,576 ≈ 103.2 MB. So about 103 MB. That's definitely < 256 MB. So it's fine.
But there is also overhead of vector (small). So okay.
Now, time: building ps: parsing each row: for each row, we read string length L = n/4, then expand to 4 bits per char => n operations per row, total n^2 = 27M bit expansions and assignments. That's fine.
Checking: worst-case 44M block checks, each doing 4 array accesses and comparisons. That's maybe 176M operations, still okay in C++ with optimized code (likely within 2 seconds? Might be borderline but probable). We can micro-opt: use local variables, avoid function calls, use integer arithmetic.
We could also optimize by early exit: as soon as we find a failing block, we break out. For many x that are not valid, we might break early after checking few blocks. So average case could be faster.
But still worst-case could be when answer is 1 (the smallest x) and we test all divisors from largest down to 1. For n=5040 (many divisors), we test many x until we find 1 works. For each x, we might check many blocks before failing. In worst case, each x we test might check all blocks before finding a failure. That would be sum_{d|n, d>1} (n/d)^2 + (n/1)^2 (since x=1 always works). But note that for x=1, (n/1)^2 = n^2 checks, and for x>1, we also do checks. But note that if matrix is random, we might fail early for large x (first block). However worst-case scenario: matrix is such that all blocks of size x are uniform except one? Actually to cause maximum checks we could design matrix that is all zeros except one cell? But then for large x, block containing that cell would fail only at the very last block? But we can check blocks in order; we can break at first failure. For worst-case to maximize checks, we want each x to pass all blocks except maybe the last one? But if a block fails, we break early; we want to delay failure as much as possible for each x, so we could arrange the non-uniform block to be the last one checked. But we cannot control order? We check blocks in increasing I and J. So we could set the non-uniform block to be at the end (bottom right). That would cause us to check all blocks for that x before finding failure. So worst-case, for each x, we might check all (n/x)^2 blocks. And then for x=1, we check all n^2 blocks and it passes. So total checks = sum_{d|n} (n/d)^2. This sum is bounded by about 1.6449 n^2 as argued. For n=5200, n^2=27e6, times 1.64 = 44.3 million. That's not huge. 44 million block checks, each with 4 array accesses and a couple comparisons, maybe 200 million operations, which in C++ might be around 0.2-0.5 seconds? Actually 44 million is moderate. But note that block checks for x=1: (n/1)^2 = 27 million blocks? Wait n^2 is 27 million. So for x=1, we are checking 27 million blocks! But that's included in the sum. Actually n^2 = 27 million. The sum_{d|n} (n/d)^2 includes term for d=1: (n)^2 = 27 million. The rest add up to about 17 million. So total ~44 million. So block checks ~44 million. Each block check: compute sum via 4 array accesses and some arithmetic, then compare to 0 and x*x. That's maybe 10 operations. So ~440 million operations? Might be borderline but likely okay with optimized C++ (maybe 1 second). Also building ps involves 27 million operations. So total maybe 70 million operations. Should be fine.
But there is also parsing and converting hex, which is also O(n^2). So total operations maybe 100 million. That's okay.
Now, I think this solution is acceptable.
Potential pitfalls: The hex conversion: uppercase letters A-F. We need to ensure we read exactly n/4 characters per line. But what if lines have trailing newline? cin >> string will ignore leading whitespace and read until whitespace. Since there are no spaces, it will read the whole line. But if a line might be empty? No.
Now, confirm that we treat bits in the correct order: For hex digit 'E' (14 decimal, binary 1110). Example: In first sample, first line "E7". E7 in binary: E=1110, 7=0111? Actually 7 is 0111. So the first 8 bits: 1110 0111 = 11100111. That matches the sample: "11100111". Good.
Now, while building ps, we fill from column 1 to n. For each bit, we add to cur_sum and set ps[i][col] accordingly.
Now, note: The ps array is (n+1) x (n+1), with indices 0..n. We'll keep row 0 and col 0 as zeros (initialized). For i from 1..n, we compute cur_sum from 0. For col from 1..n: after processing bit, we set ps[i][col] = ps[i-1][col] + cur_sum.
But we need to access ps[i-1][col] which is computed in previous row. For col index, we use offset: base = i*(n+1); prev_base = (i-1)*(n+1). So:
cur_sum = 0;
for col = 1..n:
bit = next bit from hex expansion
cur_sum += bit;
ps[base + col] = ps[prev_base + col] + cur_sum;
But we also need to set ps[i][0] = 0 for all i? In flat array, we can set all elements to 0 initially, and never assign to column 0? Actually we need to have column 0 entries for later prefix sum queries. They should be zero. Since we zero-initialize the whole vector, ps[i* (n+1) + 0] is 0 for all i. That's fine. Similarly row 0 entries are zero.
Now, after building ps, we check divisors.
Now, one more nuance: The input guarantee n divisible by 4. But n up to 5200. So n/4 integer.
Now, we should handle case where n is large but maybe n=5200. We need to ensure we use fast input. We'll use ios::sync_with_stdio(false); cin.tie(0); cout.tie(0). Then read n as int.
Now, after reading n, we need to allocate ps. For n=5200, (n+1)*(n+1) = 27,048,401 ints. That's large; we need to ensure we allocate as a single vector. We'll do:
vector ps((n+1)*(n+1), 0);
But constructing a vector of 27 million ints with zero initialization might take some time, but it's O(n^2) and acceptable.
Alternatively, we could allocate using a global array of static size? But n is up to 5200, so max size known, we could use static array int ps[5201][5201] if memory is stack? That would be too large for stack. So dynamic allocation is necessary.
Now, we need to be careful about the indexing function: inline int idx(int i, int j) { return i * (n+1) + j; }. We'll precompute stride = n+1.
Now, parsing:
string line;
getline(cin, line)? Actually after reading n, we have newline. If we use cin >> n, then there is a newline. Then we want to read n lines. We can use cin.ignore() to consume the newline? But if we use cin >> for each row string, it will skip leading whitespace, so the newline after n is whitespace, so it will skip it automatically. So we can do:
cin >> n;
vector ps(...);
int stride = n+1;
for (int i = 1; i <= n; ++i) {
string s;
cin >> s; // this will read next token, which is the row string (no spaces)
// But note: if there are spaces in the line? No.
// However, if the line length is n/4, but maybe there could be leading/trailing whitespace? Not expected.
// Ensure that s length is exactly n/4. If it's shorter due to some issue, we may need to pad? But we trust input.
int cur_sum = 0;
int base = i * stride;
int prev_base = (i-1) * stride;
int col = 1;
for (char c : s) {
int val;
if (c >= '0' && c <= '9') val = c - '0';
else val = c - 'A' + 10;
// process bits from MSB to LSB
for (int shift = 3; shift >= 0; --shift) {
int bit = (val >> shift) & 1;
cur_sum += bit;
ps[base + col] = ps[prev_base + col] + cur_sum;
col++;
}
}
// after loop, col should be n+1
}
But we need to ensure that the number of bits processed equals n. Since s length = n/4, and each yields 4 bits, total n bits.
Now, after building ps, compute divisors:
vector divisors;
for (int d = 1; d*d <= n; ++d) {
if (n % d == 0) {
divisors.push_back(d);
if (d != n/d) divisors.push_back(n/d);
}
}
sort(divisors.begin(), divisors.end(), greater());
Now iterate:
for (int x : divisors) {
int blocks = n / x;
bool ok = true;
// check each block
for (int I = 1; I <= blocks; ++I) {
int r1 = (I-1)x;
int r2 = Ix;
// compute base row indices? We'll use them inside column loop.
for (int J = 1; J <= blocks; ++J) {
int c1 = (J-1)x;
int c2 = Jx;
int sum = ps[r2stride + c2] - ps[r1stride + c2] - ps[r2stride + c1] + ps[r1stride + c1];
if (sum != 0 && sum != x*x) {
ok = false;
break;
}
}
if (!ok) break;
}
if (ok) {
cout << x << endl;
return 0;
}
}
Note: We didn't consider that the answer must be at least 1, but we will find it at the end.
Now, we must ensure that x divides n; but we already generate divisors.
Edge Cases: If n is prime? But n divisible by 4, so n>=4 composite.
Now, verify correctness on some small cases:
Case: n=4, all zeros. Then divisors: 4,2,1. Check x=4: blocks=1, sum=0 => ok => output 4.
Case: n=4, matrix: row1: 0000, row2: 0000, row3: 1111, row4: 1111. Check x=2: blocks=2. Blocks: top-left 2x2 all 0 => sum 0 ok. top-right 2x2 all 0? Actually rows 1-2, cols 3-4: but all zeros? row1 col3? row1 col3 = 0, row2 col3=0, so sum 0 ok. bottom-left 2x2 rows 3-4 cols1-2: all 1? sum 4 = 2*2 ok. bottom-right sum 4 ok. So x=2 works. Also x=4? whole matrix sum 8, not 0 or 16 -> fail. So answer 2. Our algorithm should output 2.
Now, check that the prefix sum computation is correct. For that matrix, we'll have bits. Should work.
Now, note: We used int for ps, but sum could be up to n^2 = 27M, int is fine.
Now, about speed: The block checking loops are nested I,J. For x small like 1, blocks = n, so we have n^2 = 27M iterations. That's the heaviest. But we only check x=1 if none of the larger divisors work. So worst-case scenario, we check all divisors including 1. The sum of (n/x)^2 across divisors is about 44M. So 44M iterations, each with a few operations. That's fine.
Potential micro-optimizations:
Use local variable for stride, ps pointer (ps.data()).
In the block check, we can precompute x2 = xx. Also, for each I, compute r1, r2, and also maybe precompute base rows: int base_r2 = r2stride, base_r1 = r1*stride. Then inside J loop, compute c1, c2, and then sum = ps[base_r2 + c2] - ps[base_r1 + c2] - ps[base_r2 + c1] + ps[base_r1 + c1].
But note: r1 and r2 are fixed per I, so base_r2 and base_r1 are fixed. So we can compute those once per I. Then inside J loop, we compute c1, c2, and then sum = ps[base_r2 + c2] - ps[base_r1 + c2] - ps[base_r2 + c1] + ps[base_r1 + c1]; This avoids multiplication inside loops.
So:
for (int I = 1; I <= blocks; ++I) {
int r1 = (I-1)x;
int r2 = Ix;
int base_r1 = r1 * stride;
int base_r2 = r2 * stride;
for (int J = 1; J <= blocks; ++J) {
int c1 = (J-1)x;
int c2 = Jx;
int sum = ps[base_r2 + c2] - ps[base_r1 + c2] - ps[base_r2 + c1] + ps[base_r1 + c1];
if (sum != 0 && sum != x*x) {
ok = false; break;
}
}
if (!ok) break;
}
We can also precompute x*x as square.
Now, we should also note that the prefix sum array is of type int, but for large n, indexing with int is fine.
Now, about reading input: using cin >> string may be slower than getline. But with sync off, it's okay. However, we might have to handle lines where string length is exactly n/4, but if there are trailing spaces? Not likely. Could also use getline(cin, s). But after reading n with cin, we need to ignore the newline before getline. So we can do: cin >> n; cin.ignore(); then for each row, getline(cin, s). That might be simpler, but getline reads the entire line, which may include whitespace? But there is no whitespace. It also reads the newline and discards it. However, if the string might have spaces? No. I'd prefer getline to ensure we read exactly the line, but we need to be careful that the string length may be n/4. However, there might be cases where the line could have leading/trailing spaces? Probably not. So I'll use getline.
Better: after cin >> n, we have newline leftover. Use cin.ignore() to discard it. Then for i in 1..n, getline(cin, s). But ensure that s length is exactly n/4. However, sometimes lines might be empty? Not.
Alternatively, use cin >> s directly; it will skip whitespace and read the next token, which is the hex string. Since the hex strings are contiguous without spaces, that should work. The newline after n is whitespace, so it's skipped. So we can just do cin >> s; inside loop. That may be simpler. But we must ensure that there are no spaces within the line; there aren't. So fine.
Now, one more nuance: The input may contain lines with characters '0'-'9' and 'A'-'F' only. So conversion fine.
Now, about the prefix sum building: we need to fill ps for all columns. But we are only filling for column indices 1..n. Column 0 remains 0. Also row 0 is all zeros. That's set by vector initialization.
But note: In the loop we compute ps[base + col] using ps[prev_base + col] which is from previous row. This works because we have already filled previous row. For row i=1, prev_base is 0, and ps[prev_base+col] is 0 (since row 0 all zero). So ps[1][col] = cur_sum, which is cumulative sum of row1 up to col. That's correct.
Now, check correctness of ps for block sums: For a block from r1+1 to r2, c1+1 to c2 inclusive, sum = ps[r2][c2] - ps[r1][c2] - ps[r2][c1] + ps[r1][c1]. Our indices: r1 = (I-1)x, r2 = Ix, similarly for columns. Since ps is inclusive of indices, r1 is the index before the block's first row, r2 is the last row index. That's correct.
Now, we need to ensure that for x dividing n, r2 = I*x <= n, which is true. r1 = (I-1)*x >=0.
Now, we must be careful about integer types: int is fine.
Now, test with sample:
Sample 1: n=8. Build ps. Check divisors of 8: 8,4,2,1. For x=8: blocks=1, sum = total sum. Let's compute total sum? The matrix described: first three rows: E7 -> 11100111 -> 6 ones? Actually 11100111 has 6 ones? Count: 1,1,1,0,0,1,1,1 => 6 ones? Wait count: positions: 1:1,2:1,3:1,4:0,5:0,6:1,7:1,8:1 => 6 ones. So each of rows 1-3 have 6 ones. Row4: 00 -> 00000000 => 0 ones. Row5: 00 -> 0 ones. Row6-8: E7 -> each 6 ones. So total sum = 36 + 0 + 0 + 36 = 36 ones? Actually 66=36? No 6 ones per row, 6 rows (1-3,6-8) -> 66=36. So total = 36. x=8, x*x=64, sum=36 not 0 nor 64 -> fail. x=4: blocks=2. Let's test: Block (1,1): rows1-4, cols1-4. That block contains part of rows1-3 with ones, row4 zeros. Probably not uniform. So fail. x=2: blocks=4. Check. Might fail. x=1: passes always. So answer 1. Good.
Sample2: n=4, divisors: 4,2,1. For x=4, total sum? Rows: 7 (0111) -> 3 ones? 0+1+1+1=3, rows2-4: F (1111) -> 4 each, total = 3+4+4+4=15. x*x=16, not 0, not 16 -> fail. x=2: blocks=2. Block (1,1): rows1-2, cols1-2: row1 bits: 0,1; row2:1,1 -> not uniform (0 and 1 present). So fail. x=1: pass. answer 1.
Now, we must confirm that for x=1, we check n^2 blocks (each cell). For each block (size 1), sum = cell value (0 or 1). Condition: sum == 0 or 1? x*x =1. So sum must be 0 or 1. Since each cell is either 0 or 1, it's always true. So pass.
Now, we need to ensure we consider only x that divide n. We'll generate divisors.
Now, potential memory/time issues: The vector ps with 27 million ints. Using vector may cause memory fragmentation? Usually it's contiguous, so fine. But we need to be careful with the default allocator; it's okay.
But we might also consider using short to reduce memory, but int is safe.
Now, some micro-optimizations:
Use resize and fill? Actually vector ps((n+1)*(n+1), 0) will allocate and initialize all to 0, which is okay.
Use int* ptr = ps.data() for faster indexing.
But we can just use vector and compute index each time. However, in the inner loops for block checks, we will be accessing ps many times; we could store pointer to data.
I'll implement as:
int N = n;
int stride = N+1;
vector ps(stride*(N+1), 0); // total size (N+1)(N+1)
int p = ps.data(); // use raw pointer for speed
Then in loops: p[base + col] etc.
Also, in building ps:
int* prev = p + (i-1)stride;
int cur = p + i*stride;
for col... {
cur[col] = prev[col] + cur_sum;
}
But careful: cur[0] is not set, but remains 0.
Now, block check:
for (int I = 1; I <= blocks; ++I) {
int r1 = (I-1)x;
int r2 = Ix;
int* row2 = p + r2stride;
int row1 = p + r1stride;
for (int J = 1; J <= blocks; ++J) {
int c1 = (J-1)x;
int c2 = Jx;
int sum = row2[c2] - row1[c2] - row2[c1] + row1[c1];
if (sum != 0 && sum != xx) {
ok = false;
break;
}
}
if (!ok) break;
}
That's efficient.
Now, about conversion from hex: we can precompute a lookup table for 4 bits for each hex char. For speed, we can have an array hexVal[256] mapping char to integer, and maybe also an array bits[16][4] for the four bits. But it's not necessary; simple bit operations are fine.
But we need to process n/4 characters per row, each expanding to 4 bits. So total bits = n^2. n^2 up to 27 million, so 27 million bit extractions. That's fine.
We can also precompute a table mapping char to an array of 4 bits, or mapping to integer, then in the inner loop we extract bits via shift. But shift operations are cheap.
However, we could precompute for each hex char the 4-bit pattern as an integer (0..15) and then use a small loop to output bits. That's what we do.
Now, one more micro-optimization: Instead of processing each bit individually, we could compute cumulative sums per row differently: For each hex digit, we have 4 bits; we can update cur_sum for each bit and set cur[col]. But we can also compute the prefix sum for the row after parsing all bits, but we need the cur_sum incremental to assign per column.
Given that n is moderate, fine.
Now, we must ensure we handle the case where the input lines may have leading zeros? That is fine.
Now, potential pitfalls: When n=5200, reading lines with cin >> string may be slow due to allocation? But we can use std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); Then cin >> string should be fast enough.
Now, alternative: Use getline and reserve? Not needed.
Now, we need to compile with optimizations -O2.
Now, we should test on a simple case.
Let's simulate n=4, matrix all zeros.
Input:
4
0
0
0
0
But each line must have n/4 = 1 hex digit. '0' -> bits 0000. So matrix all zeros. Then divisors: 4,2,1. x=4: sum=0 => ok, output 4. Works.
Now, matrix all ones: All lines with 'F'? For n=4, each line 'F' -> 1111, sum total = 16, x=4 ok.
Now, matrix with pattern: 2x2 blocks of zeros and ones. For n=4, rows: 00? Actually need 2x2 blocks. For example: first two rows: 00 (hex 0) -> 0000; next two rows: FF (hex F) -> 1111. Input lines: n=4, so each line one hex digit. So lines: 0,0,F,F. So matrix: rows1-2: 0000; rows3-4: 1111. This yields x=2 works? Check: blocks of size 2: top-left: rows1-2 cols1-2 all 0, sum 0 ok; top-right: rows1-2 cols3-4 all 0, sum 0 ok; bottom-left: rows3-4 cols1-2 all 1, sum 4 ok; bottom-right: rows3-4 cols3-4 all 1, sum 4 ok. So answer should be 2. Our algorithm should produce 2.
Now, verify: For x=4, total sum = 16? Actually total sum = 8? Wait rows1-2 zeros (0), rows3-4 all ones: 4*4? Actually each row has 4 ones, so rows3-4: 2 rows * 4 ones = 8. total = 8. x=4: block sum =8, not 0 or 16 -> fail. x=2 works. So output 2.
Now, we need to ensure that we check divisors in descending order; we will output 2.
Now, we must consider that the answer is maximum x. So we start from largest divisor.
Now, there is also possibility that x=1 always works, so we will never get to the end without answer.
Now, note: We need to output maximum x, not necessarily n. Good.
Now, let's think about potential integer overflow in prefix sums: Sum could be up to n*n = 27e6, fits in int.
Now, memory: 103 MB for ps. In some judges, memory limit might be 256 MB, so okay.
But wait, we also need to store the vector of divisors (size up to ~100). Fine.
Now, the input itself: reading n lines of strings; each string length up to 1300, total characters ~ n * n/4 = n^2/4 = about (5200^2)/4 = 27M/4 = 6.75M characters, which is okay.
Now, overall solution is straightforward.
But there is a nuance: The input description says "Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input." So they emphasize fast input. We'll use fast IO.
Now, possible alternative approach: Without building full prefix sums, we could check uniformity using GCD of periods? But prefix sum is simple.
Now, we should ensure we don't have off-by-one errors in indexing. Let's test with small n manually.
Suppose n=2, but n must be divisible by 4? Actually n divisible by 4, so n>=4. So ignore n=2.
Test with n=4, all zeros. Build ps:
Row1: bits: 0 0 0 0. cur_sum increments 0 each. So ps[1][1]=0, ps[1][2]=0, ps[1][3]=0, ps[1][4]=0.
Row2: all zeros, ps[2][1]=ps[1][1]+0=0, etc.
Row3: zeros, Row4: zeros.
So ps[4][4]=0.
Check x=2: blocks=2.
For I=1,J=1: r1=0, r2=2, c1=0, c2=2. sum = ps[2][2] - ps[0][2] - ps[2][0] + ps[0][0] = 0 - 0 - 0 + 0 = 0. Good.
I=1,J=2: r1=0, r2=2, c1=2, c2=4: sum = ps[2][4] - ps[0][4] - ps[2][2] + ps[0][2] = 0-0-0+0=0.
I=2,J=1: r1=2, r2=4, c1=0, c2=2: sum = ps[4][2] - ps[2][2] - ps[4][0] + ps[2][0] = 0-0-0+0=0.
I=2,J=2: r1=2, r2=4, c1=2, c2=4: sum = ps[4][4] - ps[2][4] - ps[4][2] + ps[2][2] = 0-0-0+0=0.
All uniform, so x=2 passes? Actually we expected x=4 passes but x=2 also passes? For all zeros, any x that divides n should pass because each block is uniform (all zeros). So x=2 also passes. But maximum x is 4, so we should check x=4 first. Our algorithm checks divisors descending: 4,2,1. For x=4, blocks=1, sum=0 -> passes, so output 4. So good.
Now test with n=4, pattern: rows: 0,0,F,F as described. Build ps accordingly.
Now check x=2:
I=1,J=1: r1=0,r2=2,c1=0,c2=2 => sum = ps[2][2] - 0 - 0 + 0 = 0 -> ok.
I=1,J=2: r1=0,r2=2,c1=2,c2=4 => sum = ps[2][4] - ps[0][4] - ps[2][2] + ps[0][2] = 0 - 0 - 0 + 0 = 0 -> ok.
I=2,J=1: r1=2,r2=4,c1=0,c2=2 => sum = ps[4][2] - ps[2][2] - ps[4][0] + ps[2][0] = 4 - 0 - 0 + 0 = 4 -> x*x=4 => ok.
I=2,J=2: r1=2,r2=4,c1=2,c2=4 => sum = ps[4][4] - ps[2][4] - ps[4][2] + ps[2][2] = 8 - 0 - 4 + 0 = 4 -> ok.
So x=2 passes. Good.
Now, if we have a matrix that is not uniform for x=2 but uniform for x=1 only, we will test x=4 and x=2 first, they will fail, then x=1 pass.
Now, check x=2 fail condition: Example from first sample. Let's test a simple case: matrix:
Row1: 1 0
Row2: 0 1
But n=2 not allowed. For n=4, maybe a checkerboard 2x2 blocks? Actually for x=2 to fail, a 2x2 block must contain both 0 and 1. So yes.
Now, we must also consider if the matrix is uniform for some x but not for larger multiples? For example, x=2 works but x=4 doesn't. That's typical.
Now, algorithm seems correct.
Now, edge case: n=5200, but maybe there are many divisors; but sum of (n/x)^2 across divisors is bounded, as argued.
Now, let's compute exactly worst-case sum for n=5040 (highly composite). Divisors: many, but sum_{d|n} (n/d)^2 = n^2 * sum_{d|n} 1/d^2. The sum of reciprocals of squares of divisors is at most sum_{k=1}^{∞} 1/k^2 = π^2/6 ≈ 1.6449. But note that divisors are not all integers; they are only divisors of n. However the maximum of sum_{d|n} 1/d^2 over n is attained when n has many small divisors. For n with many divisors like 5040, divisors include 1,2,3,4,5,6,7,8,9,10,12,... up to 5040. The sum of 1/d^2 for d dividing 5040: approximate sum of reciprocals of squares of these numbers. Since 5040 has many small divisors, it might be close to sum_{k=1}^{∞} 1/k^2 but missing some primes? Actually includes all numbers up to 12? Not exactly. But it will be less than 1.6449. So bound holds.
Now, we also need to consider that for each block we do 4 array accesses and some arithmetic/comparisons; 44 million blocks is fine.
Now, we should also consider the time to compute divisors and sort; negligible.
Now, the building of ps: for each row we process n bits; total n^2 = 27 million operations, each operation includes bit extraction, addition, assignment, and a few arithmetic. That's fine.
Now, overall time maybe < 1 second in optimized C++.
Now, note: We used vector with size 27 million; initialization to zero takes time but is done once; it's O(n^2) as well (27 million assignments). That's fine.
Now, we could even avoid initializing the entire vector to zero by using vector and relying on default initialization? But vector(size, 0) does initialize. We could use .resize(size) which leaves values uninitialized? But then we would need to set row0 and col0 to zero manually. It's easier to just initialize to zero. 27 million assignments is fine.
Now, we must be careful about stack size if we allocate large array locally; we allocate on heap via vector, so okay.
Now, code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
code
int n;
cin >> n;
int stride = n + 1;
vector<int> ps(stride * (n+1), 0); // (n+1) rows, each of length stride
int* p = ps.data();
// read rows
string s;
getline(cin, s); // to consume newline after n? But we used cin >> n, then we will read strings using cin >> s; that skips whitespace, so we don't need getline. However, if we use getline after cin >> n, we need to ignore newline. But using cin >> s is simpler.
// Actually we want to use cin >> s for each row. But we need to clear the newline left from reading n. However, cin >> s will skip leading whitespace, so the newline is whitespace, so it will be skipped. So no problem.
for (int i = 1; i <= n; ++i) {
cin >> s;
int cur_sum = 0;
int* cur = p + i * stride;
int* prev = p + (i-1) * stride;
int col = 1;
for (char ch : s) {
int val;
if (ch >= '0' && ch <= '9') val = ch - '0';
else val = ch - 'A' + 10;
// process 4 bits, MSB first
for (int shift = 3; shift >= 0; --shift) {
int bit = (val >> shift) & 1;
cur_sum += bit;
cur[col] = prev[col] + cur_sum;
++col;
}
}
// col should be n+1; we can assert or ignore.
}
// compute divisors of n
vector<int> divs;
for (int d = 1; d * d <= n; ++d) {
if (n % d == 0) {
divs.push_back(d);
if (d != n / d) {
divs.push_back(n / d);
}
}
}
sort(divs.begin(), divs.end(), greater<int>());
// check each x
for (int x : divs) {
int blocks = n / x;
int square = x * x;
bool ok = true;
for (int I = 1; I <= blocks; ++I) {
int r1 = (I-1) * x;
int r2 = I * x;
int* row1 = p + r1 * stride;
int* row2 = p + r2 * stride;
for (int J = 1; J <= blocks; ++J) {
int c1 = (J-1) * x;
int c2 = J * x;
int sum = row2[c2] - row1[c2] - row2[c1] + row1[c1];
if (sum != 0 && sum != square) {
ok = false;
break;
}
}
if (!ok) break;
}
if (ok) {
cout << x << '\n';
return 0;
}
}
// should never reach here as x=1 always works
cout << 1 << '\n';
return 0;
}
But there is a small bug: In the building of ps, we need to ensure that we also set cur[0] = 0 for each row? But we never set cur[0] explicitly. However, we initialized the whole vector to zero, so cur[0] is already zero. That's fine.
But note: In the block sum formula, we use row1[c1] where c1 can be 0. Since we have zero-filled, row1[0] = 0. Good.
Now, we also need to ensure that we correctly compute the cumulative sum for each row: At each column, cur_sum is the sum of bits in this row from column 1 to current column. Then cur[col] = prev[col] + cur_sum. That yields the correct 2D prefix sum.
Check: For row i, col j, we want ps[i][j] = sum_{r=1..i} sum_{c=1..j} A[r][c]. This equals sum_{r=1..i-1} sum_{c=1..j} A[r][c] + sum_{c=1..j} A[i][c] = ps[i-1][j] + cur_sum_row_i_up_to_j. So indeed cur[col] = prev[col] + cur_sum. Good.
Now, ensure that we increment col correctly: starting col = 1. For each bit, we compute and increment col. After processing all bits, col should be n+1. That's fine.
Now, note: The string s length should be n/4. But just