Cod sursa(job #3272284)

Utilizator AndreeaHzmAndreea Huzum AndreeaHzm Data 29 ianuarie 2025 03:22:20
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <climits>

#define INFINIT 1000000

using namespace std;

ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");

class Graf {
private:
    int nrNoduri;
    vector<int> *adiacenta;

public:
    explicit Graf(int nrNoduri);

    vector<vector<int>> royFloyd(vector<vector<int>> &matrice);

    ~Graf();
};

Graf::Graf(const int nrNoduri) {
    this->nrNoduri = nrNoduri;
    this->adiacenta = nullptr;
}

vector<vector<int>> Graf::royFloyd(vector<vector<int>> &matrice) {
    vector<vector<int>> distante = matrice;

    // Replace 0 (no edge) with INFINIT, except on the diagonal
    for (int i = 1; i <= nrNoduri; i++) {
        for (int j = 1; j <= nrNoduri; j++) {
            if (i != j && distante[i][j] == 0) {
                distante[i][j] = INFINIT;
            }
        }
    }

    // Floyd-Warshall Algorithm
    for (int k = 1; k <= nrNoduri; k++) {
        for (int i = 1; i <= nrNoduri; i++) {
            for (int j = 1; j <= nrNoduri; j++) {
                if (distante[i][k] < INFINIT && distante[k][j] < INFINIT) {
                    distante[i][j] = min(distante[i][j], distante[i][k] + distante[k][j]);
                }
            }
        }
    }

    // Replace INFINIT back to 0 for unreachable nodes
    for (int i = 1; i <= nrNoduri; i++) {
        for (int j = 1; j <= nrNoduri; j++) {
            if (distante[i][j] == INFINIT) {
                distante[i][j] = 0;
            }
        }
    }

    return distante;
}

Graf::~Graf() {
    delete[] adiacenta;
}

int main() {
    int n;
    fin >> n; // Number of nodes
    vector<vector<int>> matriceCosturi(n + 1, vector<int>(n + 1)); // Adjacency matrix

    // Read input matrix
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            fin >> matriceCosturi[i][j];
        }
    }

    Graf g(n);
    vector<vector<int>> distante = g.royFloyd(matriceCosturi);

    // Output the shortest path matrix
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            fout << distante[i][j] << " ";
        }
        fout << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}