Skip to content

Instantly share code, notes, and snippets.

@AnthonyBY
Last active November 4, 2017 16:27
Show Gist options
  • Save AnthonyBY/ab04ea11817d4d865347c42d6710cfe6 to your computer and use it in GitHub Desktop.
Save AnthonyBY/ab04ea11817d4d865347c42d6710cfe6 to your computer and use it in GitHub Desktop.
Stepic решение. 1.5 Решение систем линейных алгебраических уравнений
#include<iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main()
{
int i, j, n, m;
cout.precision(16); //set precision
cout.setf(ios::fixed);
cin >> n;
cin >> m;
m+=1;
double **matrix = new double *[n];
for (i=0; i<n; i++)
matrix[i] = new double [m];
for (i = 0; i<n; i++)
for (j = 0; j<m; j++) {
cin >> matrix[i][j];
}
if (n >= m) {
cout << "NO";
return 0;
}
//Метод Гаусса
//Прямой ход, приведение к верхнетреугольному виду
double tmp, xx[m];
int k;
for (i=0; i<n; i++) {
tmp=matrix[i][i];
for (j=n;j>=i;j--)
matrix[i][j]/=tmp;
for (j=i+1;j<n;j++)
{
tmp=matrix[j][i];
for (k=n;k>=i;k--)
matrix[j][k]-=tmp*matrix[i][k];
}
}
/*обратный ход*/
xx[n-1] = matrix[n-1][n];
for (i=n-2; i>=0; i--) {
xx[i] = matrix[i][n];
for (j=i+1;j<n;j++) {
xx[i]-=matrix[i][j]*xx[j];
if (isnan(xx[i])) {
cout << "NO";
return 0;
}
}
}
int isExist = true;
for (i=0; i<m;i++) {
if (isnan(xx[i])) {
isExist = false;
}
}
if (!isExist) {
cout << "NO";
return 0;
}
if (n != m-1) {
cout << "INF";
return 0;
}
//Выводим решения
cout << "YES\n";
for (i=0; i<n; i++)
cout << xx[i] << " ";
cout << endl;
delete[] matrix;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment