Pagini recente » Cod sursa (job #2065319) | Cod sursa (job #1833525) | Cod sursa (job #2907390) | Cod sursa (job #1430925) | Cod sursa (job #851249)
Cod sursa(job #851249)
#include<iostream>
#include<fstream>
#include<vector>
#include<iomanip>
#define epsilon 0.0000001
using namespace std;
void printMat(vector<vector<double> > a){
for(unsigned int i=0; i<a.size(); i++){
for(unsigned int j=0; j<a[i].size(); j++){
cout<<a[i][j]<<' ';
}
cout<<'\n';
}
cout<<'\n';
}
vector<vector<double> > read(){
ifstream f("gauss.in");
int n, m;
f>>n>>m;
vector<vector<double> > mat(n, vector<double> (++m));
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
f>>mat[i][j];
}
}
return mat;
}
bool check(double a){
if(a>0 && a-epsilon<=0)
return true;
else if(a<0 && a+epsilon>=0)
return true;
return false;
}
void swap(double &a, double &b){
int d=a;
a=b;
b=d;
}
void swapLines(vector<vector<double> > &mat, int i, int j){
for(unsigned int k=0; k<mat[0].size(); k++){
swap(mat[i][k], mat[j][k]);
}
}
void divideTwoLines(vector<vector<double> > &mat, int i, int j, int k){
for(unsigned int q=0; q<mat[0].size(); q++){
mat[j][q]-=mat[i][q]*k;
if(check(mat[j][q]))
mat[j][q]=0;
}
}
void divideOnLine(vector<vector<double> > &mat, int i, int col, double k){
for(unsigned int j=col; j<mat[0].size(); j++){
mat[i][j]/=k;
}
}
void diff(vector<vector<double> >&mat, int i, int j, double coef){
for(unsigned int k=0; k<mat[0].size(); k++){
mat[j][k]-=mat[i][k]*coef;
if(check(mat[j][k]))
mat[j][k]=0;
}
}
int main(){
vector<vector<double> > mat=read();
int i=0; //lines
int j=0; //columns
while(i<mat[0].size() && j<mat.size()){
int found=-1;
for(unsigned int k=i; k<mat.size() && found==-1; k++){
if(mat[k][j]!=0)
found=k;
}
if(found==-1){
j++;
}else{
if(found!=i)
swapLines(mat, i, found);
divideOnLine(mat, i, j, mat[i][j]);
for(int k=mat.size()-1; k>i; k--){
diff(mat, i, k, mat[k][j]);
}
i++;
j++;
}
}
vector<double> X(mat[0].size()-1);
freopen("gauss.out", "w", stdout);
for(int i=mat.size()-1; i>=0; i--){
for(int j=0; j<mat[i].size(); j++){
if(mat[i][j]!=0){
if(j==mat[i].size()-1){
printf("Imposibil");
return 0;
}
X[j]=mat[i][mat[0].size()-1];
for(int k=j+1; k<mat[i].size(); k++){
X[j]-=X[k]*mat[i][k];
}
break;
}
}
}
cout<<setprecision(7);
for(int i=0; i<X.size(); i++)
cout<<X[i]<<' ';
return 0;
}