题目链接:点击这里
题目大意:
给定一个线性方程组,对其求解
题目分析:
高斯-约旦消元法
选择一个尚未被选过的未知数作为主元,选择一个包含这个主元的方程
通过加减消元,消掉其它方程中的这个未知数
重复以上步骤,直到把每一行都变成只有一项有系数
这样就可以将矩阵变成对角矩阵了,然后获取一下答案即可
无解输出
−
1
-1
−1 ,无穷多解输出
0
0
0
时间复杂度
O
(
n
3
)
O(n^3)
O(n3)
注意:洛谷模板题数据极弱,建议用此题测试模板
具体细节见代码:
//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
//#define int ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 1e2+5;
const int mod = 998244353;
const double pi = acos(-1);
const double eps = 1e-8;
int n,cnt = 1;
double a[maxn][maxn];
int main()
{
n = read();
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n+1;j++) scanf("%lf",&a[i][j]);
for(int i = 1;i <= n;i++) // 列
{
int pos = cnt;
for(int j = cnt+1;j <= n;j++)
if(a[pos][i] < a[j][i]) pos = j;
if(fabs(a[pos][i]) < eps) continue;
for(int j = i;j <= n+1;j++) swap(a[pos][j],a[cnt][j]);
for(int j = 1;j <= n;j++)
{
if(j == cnt) continue;
double tmp = a[j][i]/a[cnt][i];
for(int k = i+1;k <= n+1;k++) a[j][k] -= tmp*a[cnt][k];
}
cnt++;
}
if(cnt <= n)
{
while(cnt <= n) if(a[cnt++][n+1] != 0) return 0*puts("-1");
return 0*puts("0");
}
for(int i = 1;i <= n;i++)
{
printf("x%d=",i);
if(fabs(a[i][n+1]/a[i][i]) < eps) puts("0.00"); // 避免出现 -0.00
else printf("%.2f\n",a[i][n+1]/a[i][i]);
}
return 0;
}