Official

A - Flip Row or Col 2 Editorial by evima


Let \(M=\lfloor \frac{N-1}{4}\rfloor\).

First, perform appropriate column flips so that the first row becomes all \(0\)s. From the state where the first row is all \(0\)s, exactly \(R_1(\leq M)\) positions can be column-flipped.

Consider each row. If the number of \(1\)s contained in a row is \(N/2\) or more, then the number of \(1\)s can be reduced by at most \(M\) through column flips, so it’s impossible to make the row sum equal to \(R_i\) (since \(R_i\leq M\lt N/2-M\)). Therefore, when the row sum is \(N/2\) or more, we should flip that row. After this processing is completed for all rows, there’s no need to perform row flips from this point onward.

Next, consider each column. Since no more row flips will be performed, the sum of column \(j\) must be either \(C_j\) or \(N-C_j\). When it’s \(N-C_j\), we flip column \(j\).

We then check whether the matrix \(A\) obtained through these operations satisfies the condition for the sum of each row.

To summarize, we can solve this problem with the following procedure:

  1. Perform column flips so that the first row becomes all \(0\)s.
  2. For each row, if the sum is \(N/2\) or more, flip that row.
  3. For each column, if the sum is \(N/2\) or more, flip that column.
  4. Check whether the obtained matrix satisfies the conditions.

The time complexity is \(O(N^2)\).

def solve():
    N = int(input())
    A = [[int(j) for j in input()] for i in range(N)]
    R = list(map(int, input().split()))
    C = list(map(int, input().split()))
    op_row = [0] * N
    op_col = [0] * N

    def flip_row(i):
        op_row[i] ^= 1
        for j in range(N):
            A[i][j] ^= 1

    def flip_col(j):
        op_col[j] ^= 1
        for i in range(N):
            A[i][j] ^= 1

    for j in range(N):
        if A[0][j] == 1:
            flip_col(j)
    for i in range(N):
        if sum(A[i]) >= (N + 1) // 2:
            flip_row(i)
    for j in range(N):
        if sum(A[i][j] for i in range(N)) >= (N + 1) // 2:
            flip_col(j)
    for i in range(N):
        if sum(A[i]) != R[i]:
            return print("No")
    for j in range(N):
        if sum(A[i][j] for i in range(N)) != C[j]:
            return print("No")

    print("Yes")
    print(*op_row, sep="")
    print(*op_col, sep="")


T = int(input())
for _ in range(T):
    solve()

posted:
last update: