fork download
#include <iostream>
#include <vector>
#include <cmath> 
#include <mpi.h>

void gaussianElimination(vector<vector<double> >& A, vector<double>& b, int rank, int size) {
    int n = A.size();
    int rows_per_process = n / size;

    for (int i = 0; i < n; ++i) {
        int maxRow;
        double maxVal = 0.0;
        for (int k = i + rank * rows_per_process; k < n; k += size * rows_per_process) {
            if (fabs(A[k][i]) > maxVal) {
                maxRow = k;
                maxVal = fabs(A[k][i]);
            }
        }
        MPI_Allreduce(MPI_IN_PLACE, &maxRow, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
        if (i % size == rank) {
            swap(A[i], A[maxRow]);
            swap(b[i], b[maxRow]);
        }
        MPI_Bcast(&A[i][0], n, MPI_DOUBLE, i % size, MPI_COMM_WORLD);
        MPI_Bcast(&b[i], 1, MPI_DOUBLE, i % size, MPI_COMM_WORLD);

        for (int k = i + 1 + rank * rows_per_process; k < n; k += size * rows_per_process) {
            double factor = -A[k][i] / A[i][i];
            for (int j = i; j < n; ++j) {
                A[k][j] += factor * A[i][j];
            }
            b[k] += factor * b[i];
        }
    }

    vector<vector<double> > global_A(n, vector<double>(n));
    vector<double> global_b(n);
    MPI_Gather(&A[0][0], rows_per_process * n, MPI_DOUBLE, &global_A[0][0], rows_per_process * n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Gather(&b[0], rows_per_process, MPI_DOUBLE, &global_b[0], rows_per_process, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        vector<double> x(n);
        for (int i = n - 1; i >= 0; --i) {
            x[i] = global_b[i] / global_A[i][i];
            for (int k = i - 1; k >= 0; --k) {
                global_b[k] -= global_A[k][i] * x[i];
            }
        }

        cout << "Solution:\n";
        for (int i = 0; i < n; ++i) {
            cout << "x[" << i << "] = " << x[i] << endl;
        }
    }
}

int main(int argc, char** argv) {
    MPI_Init(&argc, &argv);

    int rank, size;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    vector<vector<double> > A(3, vector<double>(3));
    A[0][0] = 2; A[0][1] = 1; A[0][2] = -1;
    A[1][0] = -3; A[1][1] = -1; A[1][2] = 2;
    A[2][0] = -2; A[2][1] = 1; A[2][2] = 2;

    vector<double> b(3);
    b[0] = 8; b[1] = -11; b[2] = -3;

    gaussianElimination(A, b, rank, size);

    MPI_Finalize();

    return 0;
}
Success #stdin #stdout #stderr 0.26s 40712KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "void gaussianElimination"
Execution halted