洛谷 P3389 【模板】高斯消元法

题目传送门

模板题.

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

using namespace std;

double a[101][105],n;

inline double mx() {
	double s = 0,w = 1;
	char ch = getchar();
	while(ch < '0' || ch > '9') {
		if(ch == '-') w = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9') {
		s = s * 10.0 + double(ch - '0');
		ch = getchar();
	}
	return s * w;
}

int main() {
	n = mx();
	for(int i = 1;i <= n; i++)
		for(int j = 1;j <= n + 1; j++)
			a[i][j] = mx();
	for(int i = 1;i <= n; i++) {
		int id = i;
		double m = fabs(a[i][i]);
		for(int j = i + 1;j <= n; j++)
			if(fabs(a[j][i]) > m)
				m = fabs(a[j][i]),id = j;
		for(int j = 1;j <= n + 1; j++)
			swap(a[id][j],a[i][j]);
		if(a[i][i] == 0) {
			printf("No Solution");
			return 0;
		}
		for(int j = 1;j <= n; j++) {
			if(i == j) continue;
			double tm = a[j][i] / a[i][i];
			for(int k = i + 1;k <= n + 1; k++)
				a[j][k] -= tm * a[i][k];
		}
	}
	for(int i = 1;i <= n; i++)
		printf("%.2lf\n",a[i][(int)n+1] / a[i][i]);
	return 0;
} 
posted @ 2020-11-04 20:24  Mr^Simon  阅读(102)  评论(0编辑  收藏  举报