# 高斯消元模板

模板:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;
typedef long long ll;
const int N = 1e3 + 15;
const double eps = 1e-6;

int n;
double a[N][N];

int gauss()
{
	int c, r;  
	for(c = 0, r = 0; c < n; ++ c){
		int t = r;
		for(int i = r; i < n; ++ i)
			if(fabs(a[i][c]) > fabs(a[i][t]))
				t = i;

		if(fabs(a[t][c]) < eps) continue;

		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];
		for(int i = r + 1; i < n; ++ i)
			if(abs(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)
				return 2;
		return 1;
	}

	for(int i = n - 1; i >= 0; -- i)
		for(int j = i + 1; j < n; ++ j){
			a[i][n] -= a[i][j] * a[j][n];
		}

	return 0;
}

int main()
{
    scanf("%d",&n);
	for(int i = 0; i < n; ++ i){
		for(int j = 0; j <= n; ++ j) scanf("%lf",&a[i][j]);
	}

	int t = gauss();

	if(t == 2) printf("No solution\n");
	else if(t == 1) printf("Infinite group solutions\n");
	else {
		for(int i = 0; i < n; ++ i) printf("%.2lf\n",a[i][n]);
	}
	return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>

using namespace std;
typedef long long ll;
const int N = 1e3+5;

double b[N], c[N][N];
int n;


int main()
{
    scanf("%d",&n);
    for(int i = 1; i <= n ; ++ i){
        for(int j = 1; j <= n ; ++ j){
            scanf("%lf", &c[i][j]);
		}
		scanf("%lf", &b[i]);
	}
    pr();

    //高斯消元
    for(int i = 1; i <= n; ++ i){       //遍历处理第i行
        int flag=0;
        for(int j = i; j <= n; ++ j){       //处理第i行以下的第j行
            if(fabs(c[j][i]) > 1e-8){       //如果第j行i列值大于0,就交换i,j行,加break就只把第一个不为0的行与i行交换
                flag=1;
                for(int k = 1; k <= n; ++ k) swap(c[i][k], c[j][k]);
                swap(b[i], b[j]);
                break;
            }
        }
        //无解情况
        if(!flag){
            printf("No Solution\n");
            return 0;
        }
        //给第j行的值都减去第i行的值乘a[i][i](小于i的列都处理成0了)
        for(int j = 1; j <= n; ++ j){//j遍历行1~n(除了i);
            if(i == j) continue;
            double rate = c[j][i] / c[i][i];
            for(int k = i; k <= n; ++ k) c[j][k] -= c[i][k] * rate;  // k遍历i~n列
            b[j] -= b[i] * rate;
        }
    }
    for(int i = 1; i <= n; ++ i) printf("%.2lf\n",b[i]/c[i][i]);
    return 0;
}

posted @ 2020-02-16 22:05  A_sc  阅读(125)  评论(0编辑  收藏  举报