Skip to content

Commit 2a215e9

Browse files
authored
Create Gaussian Elimination.cpp
1 parent 425b6d8 commit 2a215e9

File tree

1 file changed

+145
-0
lines changed

1 file changed

+145
-0
lines changed

Gaussian Elimination.cpp

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
//Intermediary
2+
//Young kid on the block
3+
//AIAsif try's Continuing the journey
4+
#include<bits/stdc++.h>
5+
#include <ext/pb_ds/assoc_container.hpp>
6+
#include <ext/pb_ds/tree_policy.hpp>
7+
using namespace std;
8+
using namespace __gnu_pbds;
9+
#define endl "\n"
10+
#define int long long int
11+
#define ordered_set tree< int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update>
12+
13+
14+
const double eps = 1e-9;
15+
16+
int Gauss(vector<vector<double>> a, vector<double> &ans)
17+
{
18+
int n = (int)a.size(), m = (int)a[0].size() - 1;
19+
vector<int> pos(m, -1);
20+
double det = 1;
21+
int rank = 0;
22+
23+
24+
for (int col = 0, row = 0; col < m && row < n; ++col)
25+
{
26+
int mx = row;
27+
for (int i = row; i < n; i++)
28+
{
29+
if (fabs(a[i][col]) > fabs(a[mx][col]))
30+
{
31+
mx = i;
32+
}
33+
34+
}
35+
36+
if (fabs(a[mx][col]) < eps)
37+
{
38+
det = 0;
39+
continue;
40+
}
41+
for (int i = col; i <= m; i++)
42+
{
43+
swap(a[row][i], a[mx][i]);
44+
}
45+
46+
if (row != mx)
47+
{
48+
det = -det;
49+
}
50+
51+
det *= a[row][col];
52+
pos[col] = row;
53+
for (int i = 0; i < n; i++)
54+
{
55+
if (i != row && fabs(a[i][col]) > eps)
56+
{
57+
double c = a[i][col] / a[row][col];
58+
for (int j = col; j <= m; j++)
59+
{
60+
a[i][j] -= a[row][j] * c;
61+
}
62+
63+
}
64+
}
65+
++row;
66+
++rank;
67+
}
68+
ans.assign(m, 0);
69+
for (int i = 0; i < m; i++)
70+
{
71+
if (pos[i] != -1)
72+
{
73+
ans[i] = a[pos[i]][m] / a[pos[i]][i];
74+
}
75+
76+
}
77+
for (int i = 0; i < n; i++)
78+
{
79+
double sum = 0;
80+
for (int j = 0; j < m; j++)
81+
{
82+
sum += ans[j] * a[i][j];
83+
}
84+
85+
if (fabs(sum - a[i][m]) > eps)
86+
{
87+
return -1; // no solution
88+
}
89+
90+
}
91+
for (int i = 0; i < m; i++)
92+
{
93+
if (pos[i] == -1)
94+
{
95+
return 2; // infinte solutions
96+
}
97+
98+
}
99+
100+
return 1; // unique solution
101+
}
102+
103+
104+
105+
106+
int32_t main()
107+
{
108+
ios::sync_with_stdio(0);
109+
cin.tie(0);
110+
111+
112+
int n, m;
113+
cin >> n >> m;
114+
115+
vector<vector<double>> v(n);
116+
for (int i = 0; i < n; i++)
117+
{
118+
for (int j = 0; j <= m; j++) // m-th colunm contain the value of constant
119+
{
120+
double x;
121+
cin >> x;
122+
v[i].push_back(x);
123+
}
124+
}
125+
vector<double> ans;
126+
127+
int k = Gauss(v, ans);
128+
129+
if (k)
130+
{
131+
for (int i = 0; i < n; i++)
132+
{
133+
cout << fixed << setprecision(5) << ans[i] << ' ';
134+
}
135+
136+
}
137+
else
138+
{
139+
cout << "no solution"<<endl;
140+
}
141+
142+
return 0;
143+
144+
145+
}

0 commit comments

Comments
 (0)