Cod sursa(job #3283949)

Utilizator Vesel_MateiVesel Denis Matei Vesel_Matei Data 10 martie 2025 18:56:59
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

const int INF = 1e6; // O valoare mare pentru a simula infinitul

void floyd_warshall(vector<vector<int>>& dist, int n) {
    for (int k = 0; k < n; k++) {       // Nod intermediar
        for (int i = 0; i < n; i++) {   // Nod sursă
            for (int j = 0; j < n; j++) { // Nod destinație
                if (dist[i][k] != INF && dist[k][j] != INF) {
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
                }
            }
        }
    }

    // Înlocuim INF cu 0 pentru a respecta cerințele problemei
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (dist[i][j] == INF) {
                dist[i][j] = 0;
            }
        }
    }
}

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

    int n;
    fin >> n;

    vector<vector<int>> dist(n, vector<int>(n));

    // Citim matricea de distanțe și înlocuim 0-urile cu INF, exceptând diagonala principală
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            fin >> dist[i][j];
            if (i != j && dist[i][j] == 0) {
                dist[i][j] = INF;
            }
        }
    }

    floyd_warshall(dist, n);

    // Scriem rezultatul în fișierul de ieșire
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            fout << dist[i][j] << " ";
        }
        fout << endl;
    }

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