AcWing 883. 高斯消元解线性方程组
原题链接
简单
作者:
我要出去乱说
,
2021-01-21 14:21:20
,
所有人可见
,
阅读 432
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 110;
const double eps = 1e-6;
int n;
double a[N][N];
int gauss()
{
int c, r; //r表示当前所在的行数,c表示当前所指向的列数
for (c = 0, r = 0; c < n; c ++ )
{
int t = r; //t代表列最大值所在的行
for (int i = r; i < n; i ++ ) //找到第c列最大系数绝对值
if (fabs(a[i][c]) > fabs(a[t][c]))
t = i;
if (fabs(a[t][c]) < eps) continue; //如果最大值是0,跳过该循环进入下一列循环
for (int i = c; i <= n; i ++ ) swap(a[t][i], a[r][i]); //将最大行与当前行逐个元素进行交换
for (int i = n; i >= c; i -- ) a[r][i] /= a[r][c]; //将当前行c位的值初始化为1,当前行其他元素也要除以这个数
for (int i = r + 1; i < n; i ++ )
if (fabs(a[i][c]) > eps)
for (int j = n; j >= c; j -- )
a[i][j] -= a[r][j] * a[i][c];
r ++ ;
}
if (r < n)
{
for (int i = r; i <= n; i ++ )
if (fabs(a[i][n] > eps)) //即出现0 == 非零的情况
return 2; //无解
return 1; //有无穷多解
}
for (int i = n - 1; i >= 0; i -- ) //此处i = n - 1或i = n - 2都是对的
for (int j = i + 1; j < n; j ++ )
a[i][n] -= a[i][j] * a[j][n]; //a[j][n]就是xj的值
return 0; //有唯一解
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n + 1; j ++ )
cin >> a[i][j];
int t = gauss();
if (t == 0)
{
for (int i = 0; i < n; i ++ ) printf("%.2lf\n", a[i][n]);
}
else if (t == 1) puts("Infinite group solutions");
else puts("No solution");
return 0;
}