Cod sursa(job #3358426)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 16 iunie 2026 18:16:29
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
// Floyd-Warshall Algorithm
//
// Given a graph where all edges have a non-negative weight, compute the
// shortest distances for all pair of vertices.
//
// Complexity: O(n^3)

#include <bits/stdc++.h>
using namespace std;

int n;
vector<vector<int>> adj;

void floyd_warshall()
{
    for (int i = 0; i < n; i++)
        adj[i][i] = 0;

    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (adj[i][k] < INT_MAX && adj[k][j] < INT_MAX)
                    adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]);
            }
        }
    }
}

int main()
{
    freopen("royfloyd.in", "r", stdin);
    freopen("royfloyd.out", "w", stdout);

    cin >> n;
    adj.resize(n, vector<int>(n));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int x;
            cin >> x;
            adj[i][j] = (x == 0 && i != j) ? INT_MAX : x;
        }
    }

    floyd_warshall();

    for (auto &line : adj) {
        for (int num : line)
            cout << (num == INT_MAX ? 0 : num) << ' ';
        cout << '\n';
    }

    return 0;
}