日期:2025年9月6日
ZeroJudge 題目連結:d623. 反方陣
解題想法
假設矩陣 $$ M = \begin{bmatrix} a & b \\ c & d \\ \end{bmatrix} $$ 其行列式值 $det(M) = ad - bc$。如果 $det(M) \neq 0$,$M$ 是可逆的,其反矩陣 $$ M^{-1} = \frac{1}{det(M)} \begin{bmatrix} d & -b \\ -c & a \\ \end{bmatrix} $$ 另外要注意,題目的說明是4個0表示結束,實際測資以一個零表示結束。
Python 程式碼
使用時間約為 28 ms,記憶體約為 3.3 MB,通過測試。
while True:
line = list(map(int, input().split()))
if len(line) == 1 and line[0] == 0: break # 只有一個 0,中止迴圈
a, b = line # 方陣 [[a, b], [c, d]]
c, d = map(int, input().split())
det = a*d - b*c # 行列式值
if det == 0: # 沒有反方陣
print("cheat!")
else: # 反方陣 (1/det)*[[d, -b], [-c, a]]
print(f"{d/det:.5f} {-b/det:.5f}")
print(f"{-c/det:.5f} {a/det:.5f}")
使用時間約為 24 ms,記憶體約為 3.6 MB,通過測試。
import sys
result = []
lines = sys.stdin.readlines()
idx = 0
while idx < len(lines):
if not lines[idx].strip():
idx += 1
continue
if lines[idx].strip() == "0": break # 只有一個 0,中止迴圈
a, b = map(int, lines[idx].split()) # 方陣 [[a, b], [c, d]]
idx += 1
c, d = map(int, lines[idx].split())
idx += 1
det = a*d - b*c # 行列式值
if det == 0: # 沒有反方陣
result.append("cheat!\n")
else: # 反方陣 (1/det)*[[d, -b], [-c, a]]
result.append(f"{d/det:.5f} {-b/det:.5f}\n")
result.append(f"{-c/det:.5f} {a/det:.5f}\n")
sys.stdout.write("".join(result))