fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. //#include "algo/debug.h"
  4.  
  5. int N;
  6.  
  7.  
  8.  
  9. void gj(vector<vector<double>> A) {
  10. // Gauss-Jordan Elimination
  11. for (int k = 0; k < N; k++) {
  12. // Partial Pivoting
  13. int maxRow = k;
  14. for (int i = k + 1; i < N; i++) {
  15. if (abs(A[i][k]) > abs(A[maxRow][k])) {
  16. maxRow = i;
  17. }
  18. }
  19. if (maxRow != k) {
  20. swap(A[k], A[maxRow]);
  21. }
  22.  
  23. // Make diagonal element 1
  24. double diag = A[k][k];
  25. for (int j = 0; j <= N; j++) {
  26. A[k][j] /= diag;
  27. }
  28.  
  29. // Make other elements in column 0
  30. for (int i = 0; i < N; i++) {
  31. if (i != k) {
  32. double r = A[i][k];
  33. for (int j = 0; j <= N; j++) {
  34. A[i][j] -= r * A[k][j];
  35. }
  36. }
  37. }
  38. }
  39.  
  40. // Display solutions
  41. cout << "Solution:\n";
  42. for (int i = 0; i < N; i++) {
  43. cout << "x" << i+1 << ": " << A[i][N] << endl;
  44. }
  45. }
  46.  
  47. signed main() {
  48. //freopen("Error.txt", "w", stderr);
  49. cout << "Enter N: \n";
  50. cin >> N;
  51. vector<vector<double>> A(N, vector<double>(N+1, 0));
  52.  
  53. cout << "Enter: \n";
  54. for (int i = 0; i<N; i++) {
  55. for (int j = 0; j <= N; j++) {
  56. cin >> A[i][j];
  57. }
  58. }
  59. cout << "\nGauss-Jordan Elimination:\n";
  60. gj(A);
  61. return 0;
  62. }
Success #stdin #stdout 0.01s 5284KB
stdin
3
5 10 1 28
1 1 1 6
4 8 3 29
stdout
Enter N: 
Enter: 

Gauss-Jordan Elimination:
Solution:
x1: 1
x2: 2
x3: 3