洛谷 #3389. 高斯消元解线性方程组

题意

如题

题解

自己看线代的书
对增广矩阵进行高斯消元,再回代
若当前主元系数为0,则要将下方系数不为0的方程与其交换,若找不到则无解

调试记录

#include <cstdio>
#include <cmath>
#include <cstdlib>
#define maxn 105
#define mo 1000000007
using namespace std;
int pow(int x, int t){
	x %= mo; int res = 1;
	while (t > 0){
		if (t & 1) (res *= x) %= mo;
		(x *= x) %= mo;
		t >>= 1;
	}
	return res;
}
int inv(int x){return pow(x, mo - 2);}
struct real{
	int x;
	real operator =(real a){
		x = a.x;
		return *this;
	}
	real operator +(real a){
		real res;
		res.x = (x + a.x) % mo;
		return res;
	}
	real operator +=(real a){return (*this = *this + a);}
	real operator -(real a){
		real res;
		res.x = (x - a.x + mo) % mo;
		return res;
	}
	real operator -=(real a){return (*this = *this - a);}
	real operator *(real a){
		real res;
		res.x = (x * a.x) % mo;
		return res;
	}
	real operator *=(real a){return (*this = *this * a);}
	real operator /(real a){
		real res;
		res.x = (x * inv(a.x)) % mo;
		return res;
	}
	real operator /=(real a){return (*this = *this / a);}
};
bool equ(double a, double b){return fabs(a - b) < 1e-8;}
int n;
double det[maxn][maxn];
void Gauss(){
	for (int i = 1; i <= n; i++){
		if (equ(0, det[i][i])){
			int p = i;
			for (int l = i + 1; l <= n; l++)
				if (det[l][i] > 0){
					p = l;
					break;
				}
			if (p == i){
				puts("No Solution");
				exit(0);
			}
			double temp[maxn];
			for (int j = 1; j <= n + 1; j++)
				temp[j] = det[i][j];
			for (int j = 1; j <= n + 1; j++)
				det[i][j] = det[p][j];
			for (int j = 1; j <= n + 1; j++)
				det[p][j] = temp[j];
		}
		for (int l = i + 1; l <= n; l++){
			double tmp = det[l][i] / det[i][i];
			for (int j = i; j <= n + 1; j++)
				det[l][j] -= tmp * det[i][j];
		}
	}
	for (int i = n; i >= 1; i--){
		det[i][n + 1] /= det[i][i];
		for (int l = i - 1; l >= 1; l--)
			det[l][n + 1] -= det[l][i] * det[i][n + 1];
	}
}
int main(){
	scanf("%d", &n);
	for (int i = 1; i <= n; i++){
		for (int j = 1; j <= n + 1; j++) scanf("%lf", det[i] + j);
	} 
	Gauss();
	for (int i = 1; i <= n; i++)
		printf("%.2lf\n", det[i][n + 1]);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值