Cod sursa(job #3276761)

Utilizator BogdancxTrifan Bogdan Bogdancx Data 14 februarie 2025 14:17:37
Problema Floyd-Warshall/Roy-Floyd Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <climits> // For INT_MAX

using namespace std;

int main()
{
    ifstream fin("royfloyd.in");
    ofstream fout("royfloyd.out");
    
    int n;
    fin >> n;
    
    vector<vector<int>> D(n + 1, vector<int>(n + 1, INT_MAX));
    
    // Initialize the graph distances
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            fin >> D[i][j];
            if (D[i][j] == 0 && i != j) {
                D[i][j] = INT_MAX; // Set to infinity if no path (except for diagonal)
            }
        }
    }
    
    // Floyd-Warshall Algorithm
    for(int k = 1; k <= n; k++) {
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                if(D[i][j] > D[i][k] + D[k][j]) {
                    D[i][j] = D[i][k] + D[k][j];
                }
            }
        }
    }
    
    // Output the shortest path matrix
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            if (D[i][j] == INT_MAX) {
                fout << "0 "; // For unreachable paths
            } else {
                fout << D[i][j] << ' ';
            }
        }
        fout << endl;
    }

    return 0;
}