Advertisement
leoanjos

Gauss - Correct

Mar 28th, 2023
854
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. int solve(vector<vector<ldouble>> &A, vector<ldouble> &ans) {
  2.     int rows = A.size();
  3.     int cols = A[0].size() - 1;
  4.  
  5.     int row = 0;
  6.     vector<int> where(cols, -1);
  7.  
  8.     for (int col = 0; col < cols; col++) {
  9.         int chosen = row;
  10.         while (chosen < rows && !sign(A[chosen][col])) chosen++;
  11.         if (chosen >= rows) continue;
  12.  
  13.         where[col] = row;
  14.         A[row].swap(A[chosen]);
  15.  
  16.         for (int i = 0; i < rows; i++)
  17.             if (i != row) {
  18.                 ldouble factor = A[i][col] / A[row][col];
  19.                 for (int j = col; j <= cols; j++)
  20.                     A[i][j] -= A[row][j] * factor;
  21.             }
  22.  
  23.         row++;
  24.     }
  25.  
  26.     bool freedom = false;
  27.     ans.assign(cols, 0.0L);
  28.  
  29.     for (int i = 0; i < cols; i++) {
  30.         if (where[i] == -1) freedom = true;
  31.         else ans[i] = A[where[i]][cols] / A[where[i]][i];
  32.     }
  33.  
  34.     for (int i = 0; i < rows; i++) {
  35.         ldouble sum = 0.0L;
  36.         for (int j = 0; j < cols; j++)
  37.             sum += ans[j] * A[i][j];
  38.  
  39.         if (sign(sum - A[i][cols]))
  40.             return 0;
  41.     }
  42.  
  43.     return freedom ? INF : 1;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement