备战NOIP——模板复习3
这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。
高斯消元
/*Copyright: Copyright (c) 2018
*Created on 2018-10-28
*Author: 十甫
*Version 1.0
*Title: 高斯消元
*Time: inf mins
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int size = 105;
const double eps = 1e-7;
int n;
double matrix[size][size], ans[size];
inline bool Gauss() {
for(int i = 1;i <= n;i++) {
int maxNumLine = i;
for(int j = i + 1;j <= n;j++)
if(fabs(matrix[maxNumLine][i]) < fabs(matrix[j][i]))
maxNumLine = j;
if(fabs(matrix[maxNumLine][i]) < eps)
return false;
if(i != maxNumLine)
swap(matrix[i], matrix[maxNumLine]);
double div = matrix[i][i];
for(int j = i;j <= n + 1;j++)
matrix[i][j] /= div;
for(int j = i + 1;j <= n;j++) {
div = matrix[j][i];
for(int k = i;k <= n + 1;k++) {
matrix[j][k] -= matrix[i][k] * div;
}
}
}
ans[n] = matrix[n][n + 1];
for(int i = n - 1;i >= 1;i--) {
ans[i] = matrix[i][n + 1];
for(int j = i + 1;j <= n;j++) {
ans[i] -= (matrix[i][j] * ans[j]);
}
}
return true;
}
int main() {
scanf("%d", &n);
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= n + 1;j++) {
scanf("%lf", &matrix[i][j]);
}
}
if(!Gauss()) printf("No Solution\n");
else for(int i = 1;i <= n;i++) {
printf("%.2lf\n", ans[i]);
}
return 0;
}
NOIP 2018 RP++