-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gaussian Elimination.cpp
71 lines (55 loc) · 1.98 KB
/
Gaussian Elimination.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#define MAXROW 512
#define MAXCOL 512
/***
Gauss-Jordan Elimination
n = number of linear equations
m = number of variables
ar[i][m] = right-hand side value of constants
For instance, the system of linear equations becomes:
2x + y -z = 8 -----> (i)
-3x -y + 2z = -11 -----> (ii)
-2x + y + 2z = -3 -----> (iii)
n = 3 (x, y, z), m = 3 (i, ii, iii)
ar[0] = {2, 1, -1, 8} -----> (i)
ar[1] = {-3, -1, 2, -11} -----> (ii)
ar[2] = {-2, 1, 2, -3} -----> (iii)
Returns -1 when there is no solution
Otherwise returns the number of independent variables (0 for an unique solution)
Contains a solution in the vector res on successful completion
Note that the array is modified in the process
Notes:
For solving problems on graphs with probability/expectation, make sure the graph
is connected and a single component. If not, then re-number the vertex and solve
for each connected component separately.
***/
int gauss(int n, int m, double ar[MAXROW][MAXCOL], vector<double>& res){ /// hash = 835176
res.assign(m, 0);
vector <int> pos(m, -1);
int i, j, k, l, p, free_var = 0;
for (j = 0, i = 0; j < m && i < n; j++){
for (k = i, p = i; k < n; k++){
if (abs(ar[k][j]) > abs(ar[p][j])) p = k;
}
if (abs(ar[p][j]) > EPS){
pos[j] = i;
for (l = j; l <= m; l++) swap(ar[p][l], ar[i][l]);
for (k = 0; k < n; k++){
if (k != i){
double x = ar[k][j] / ar[i][j];
for (l = j; l <= m; l++) ar[k][l] -= (ar[i][l] * x);
}
}
i++;
}
}
for (i = 0; i < m; i++){
if (pos[i] == -1) free_var++;
else res[i] = ar[pos[i]][m] / ar[pos[i]][i];
}
for (i = 0; i < n; i++) {
double val = 0.0;
for (j = 0; j < m; j++) val += (res[j] * ar[i][j]);
if (abs(val - ar[i][m]) > EPS) return -1;
}
return free_var;
}