AcWing 883. 高斯消元解线性方程组
原题链接
简单
作者:
皓首不倦
,
2020-09-04 15:29:13
,
所有人可见
,
阅读 423
'''
直接模拟计算过程即可
'''
import sys
EPSLON = 1e-7
n = int(input())
m = []
for _ in range(n):
s = sys.stdin.readline().strip()
m.append(list(map(float, s.split())))
def is_zero(val):
return abs(val) <= EPSLON
# 高斯消元
for col in range(0, n):
max_val, max_row = abs(m[col][col]), col
for row in range(col+1, n):
if abs(m[row][col]) > abs(max_val):
max_val, max_row = abs(m[row][col]), row
if is_zero(max_val):
continue
m[col], m[max_row] = m[max_row], m[col]
for row in range(col+1, n):
k = m[row][col] / m[col][col]
for j in range(col, n+1):
m[row][j] -= m[col][j] * k
flag = 0
ans = [0.0] * n
for i in range(n-1, -1, -1):
val, k = m[i][n], m[i][i]
s = 0.0
for j in range(n-1, i, -1):
s += m[i][j] * ans[j]
val -= s
if is_zero(val) and is_zero(k):
# 无穷多解
flag = 1
break
if (not is_zero(val)) and is_zero(k):
# 无解
flag = 2
break
else:
ans[i] = val / k
if flag == 1:
print('Infinite group solutions')
elif flag == 2:
print('No solution')
else:
for val in ans:
print('{:.2f}'.format(val))