Pagini recente » Cod sursa (job #2027210) | Cod sursa (job #2205192) | Cod sursa (job #1793403) | Cod sursa (job #1167138) | Cod sursa (job #2674380)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
using namespace std;
ifstream in ("gauss.in");
ofstream out("gauss.out");
int n, m;
vector <vector <long double > > mat;
const long double EPS=1e-9;
namespace GaussianElimination{
int gauss(vector <vector <long double> > mat, vector <long double> & sol){
int n=mat.size(), m=mat[0].size()-1;
vector <int> where(m, -1);
for(int lin=0, col=0; lin<n && col<m; col++){
int sel=lin;
for(int i=lin; i<n; i++)
if(abs(mat[i][col])>abs(mat[sel][col]) )
sel=i;
if(abs(mat[sel][col])<EPS)
continue;
swap(mat[sel], mat[lin]);
where[col]=lin;
for(int i=0; i<n; i++)
if(i!=lin){
long double cc=mat[i][col]/mat[lin][col];
for(int j=col; j<=m; j++)
mat[i][j]-=cc*mat[lin][j];
}
lin++;
}
sol.assign(m, 0);
for(int i=0; i<m; i++)
if(where[i]!=-1)
sol[i]=mat[where[i]][m]/mat[where[i]][i];
for(int i=0; i<n; i++){
long double sum=0;
for(int j=0; j<m; j++)
sum+=sol[j]*mat[i][j];
if(abs(sum-mat[i][m])>EPS)
return 0;
}
for(int i=0; i<m; i++)
if(where[i]==-1)
return 2; ///infinitate de solutii
return 1;
}
}
ostream & operator << (ostream & out, vector <long double> & vec){
for(auto &x:vec)
out<<fixed<<setprecision(9)<<x<<" ";
return out;
}
int main()
{
in>>n>>m;
mat.resize(n, vector<long double> (m+1));
for(int i=0; i<n; i++)
for(int j=0; j<m+1; j++)
in>>mat[i][j];
vector <long double> sol;
int rez=GaussianElimination::gauss(mat, sol);
if(rez==0)
out<<"Imposibil\n";
else if(rez==1||rez==2)
out<<sol<<"\n";
return 0;
}