結果
問題 | No.460 裏表ちわーわ |
ユーザー |
![]() |
提出日時 | 2025-03-20 21:19:02 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 579 ms / 2,000 ms |
コード長 | 3,012 bytes |
コンパイル時間 | 355 ms |
コンパイル使用メモリ | 82,724 KB |
実行使用メモリ | 76,872 KB |
最終ジャッジ日時 | 2025-03-20 21:20:11 |
合計ジャッジ時間 | 7,953 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 28 |
ソースコード
import sysdef main():M, N = map(int, sys.stdin.readline().split())a = []for _ in range(M):a.append(list(map(int, sys.stdin.readline().split())))# マス(i,j)を一列のインデックスに対応させる: idx = i*N + jtotal = M * Nmatrix = []target = []for i in range(M):for j in range(N):row = 0rhs = a[i][j]for di in (-1, 0, 1):for dj in (-1, 0, 1):ni, nj = i + di, j + djif 0 <= ni < M and 0 <= nj < N:k = ni * N + njrow |= 1 << kmatrix.append(row)target.append(rhs)# GF(2)でのガウスの消去法pivot_row = [-1] * totalrank = 0for col in reversed(range(total)): # 右から左に処理するように変更# Find the pivot rowpivot = -1for r in range(rank, total):if (matrix[r] >> col) & 1:pivot = rbreakif pivot == -1:continue# Swap with the rank rowmatrix[rank], matrix[pivot] = matrix[pivot], matrix[rank]target[rank], target[pivot] = target[pivot], target[rank]# Record the pivot row for this columnpivot_row[col] = rank# Eliminate this column in other rowsfor r in range(total):if r != rank and ((matrix[r] >> col) & 1):matrix[r] ^= matrix[rank]target[r] ^= target[rank]rank += 1# Check for inconsistencyfor r in range(rank, total):if target[r]:print("Impossible")return# Collect free variablesfree = []for col in range(total):if pivot_row[col] == -1:free.append(col)# Generate all possible values for free variables and compute the minimal flipsmin_flips = float('inf')for mask in range(0, 1 << len(free)):x = [0] * total# Set free variablesfor i in range(len(free)):if (mask >> i) & 1:x[free[i]] = 1# Process pivot columns from right to leftpivot_cols = [col for col in range(total) if pivot_row[col] != -1]pivot_cols.sort(reverse=True)for col in pivot_cols:row = pivot_row[col]bits = matrix[row]rhs = target[row]# Calculate the sum from other columnssum_val = rhsfor c in range(total):if c == col:continueif (bits >> c) & 1:sum_val ^= x[c]x[col] = sum_val# Count the number of flipsflips = sum(x)if flips < min_flips:min_flips = flipsif min_flips == float('inf'):print("Impossible")else:print(min_flips)if __name__ == "__main__":main()