Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <vector>
- using namespace std;
- vector<double> solve(vector <vector<double>> M){
- int n = M.size();
- for(int i = 0; i < n; i++){
- double max = abs(M[i][i]);
- int maxRow = i;
- for(int k = i + 1; k < n; k++){
- if(abs(M[k][i]) > max){
- max = abs(M[k][i]);
- maxRow = k;
- }
- }
- for(int k = i; k < n + 1; k++){
- double tmp = M[maxRow][k];
- M[maxRow][k] = M[i][k];
- M[i][k] = tmp;
- }
- for(int k = i + 1; k < n; k++){
- double c = -M[k][i] / M[i][i];
- for(int j = i; j < n + 1; j++){
- if(i == j)
- M[k][j] = 0;
- else
- M[k][j] += c * M[i][j];
- }
- }
- }
- vector<double> x(n);
- for(int i = n - 1; i >= 0; i--){
- x[i] = M[i][n] / M[i][i];
- for(int k = i - 1; k >= 0; k--){
- M[k][n] -= M[k][i] * x[i];
- }
- }
- return x;
- }
- int main(){
- int n;
- cin >> n;
- vector <vector<double>> M(n, vector<double>(n+1));
- for(int i = 0; i < n; i++)
- for(int j = 0; j < n; j++)
- cin >> M[i][j];
- for(int i = 0; i < n; i++)
- cin >> M[i][n];
- vector<double> x(n);
- x = solve(M);
- for(int i = 0; i < n; i++)
- cout << fixed << setprecision(2) << x[i] << " ";
- cout << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement