洛谷 #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;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章