結果

問題 No.2445 奇行列式
ユーザー lam6er
提出日時 2025-04-16 01:07:27
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,044 bytes
コンパイル時間 308 ms
コンパイル使用メモリ 82,836 KB
実行使用メモリ 162,028 KB
最終ジャッジ日時 2025-04-16 01:09:09
合計ジャッジ時間 6,377 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 5 WA * 8 TLE * 1 -- * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

n, B = map(int, input().split())
mod = 2 * B
A = [list(map(int, input().split())) for _ in range(n)]

# Compute permanent mod mod using dynamic programming
dp = [0] * (1 << n)
dp[0] = 1
for row in range(n):
    new_dp = [0] * (1 << n)
    for mask in range(1 << n):
        if bin(mask).count('1') != row:
            continue
        for col in range(n):
            if not (mask & (1 << col)):
                new_mask = mask | (1 << col)
                new_dp[new_mask] = (new_dp[new_mask] + dp[mask] * A[row][col]) % mod
    dp = new_dp
permanent = dp[(1 << n) - 1]

# Compute determinant mod mod using Gaussian elimination
def extended_gcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = extended_gcd(b % a, a)
        return (g, x - (b // a) * y, y)

def determinant_mod(matrix, mod):
    n = len(matrix)
    mat = [row.copy() for row in matrix]
    for i in range(n):
        for j in range(n):
            mat[i][j] %= mod
    det_sign = 1
    for i in range(n):
        # Find pivot
        pivot_row = -1
        for j in range(i, n):
            if mat[j][i] % mod != 0:
                pivot_row = j
                break
        if pivot_row == -1:
            return 0
        if pivot_row != i:
            mat[i], mat[pivot_row] = mat[pivot_row], mat[i]
            det_sign *= -1
        # Compute the inverse of the pivot
        a = mat[i][i]
        g, x, y = extended_gcd(a, mod)
        if g != 1:
            return 0
        inv_a = x % mod
        # Eliminate other rows
        for j in range(i+1, n):
            current_val = mat[j][i]
            if current_val == 0:
                continue
            factor = (current_val * inv_a) % mod
            for k in range(i, n):
                mat[j][k] = (mat[j][k] - factor * mat[i][k]) % mod
    # Compute product of diagonal elements
    det = 1
    for i in range(n):
        det = (det * mat[i][i]) % mod
    det = (det * det_sign) % mod
    return det

det = determinant_mod(A, mod)

ans = (permanent - det) // 2
ans %= B
print(ans)
0