Cod sursa(job #3376844)

Utilizator Cojocariu_Razvan_GeorgeCojocariu Razvan-George Cojocariu_Razvan_George Data 20 noiembrie 2026 08:41:44
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
//Algoritmul lui Dijkstra
// #include <bits/stdc++.h>
// using namespace std;
//
// const int NMAX = 5e4;
// vector<pair<int, int>> L[NMAX + 1];
// int dist[NMAX + 1], vis[NMAX + 1];
//
// int main() {
//     ifstream fin("dijkstra.in");
//     ofstream fout("dijkstra.out");
//
//     int n, m;
//     fin >> n >> m;
//     for(int i = 1; i <= m; i++) {
//         int x, y, c;
//         fin >> x >> y >> c;
//         L[x].push_back({y, c});
//     }
//     for(int i = 1; i <= n; i++) {
//         dist[i] = 1e9;
//     }
//     dist[1] = 0;
//     //(dist[node], node)
//     priority_queue<pair<int, int>> pq;
//     pq.push({-dist[1], 1});
//     while(pq.empty() == false) {
//         int nod = pq.top().second;
//         pq.pop();
//         if(vis[nod]) continue;
//         vis[nod] = 1;
//         for (auto it : L[nod]) {
//             int vec = it.first;
//             int cost = it.second;
//             if (dist[vec] > dist[nod] + cost) {
//                 dist[vec] = dist[nod] + cost;
//                 pq.push({-dist[vec], vec});
//             }
//         }
//     }
//
//     for(int i = 2; i <= n; i++) {
//         if(dist[i] == 1e9)
//             fout << 0 << " ";
//         else
//             fout << dist[i] << " ";
//     }
//     return 0;
// }

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

const int NMAX = 100;
int dist[NMAX + 1][NMAX + 1];

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

    int n;
    fin >> n;
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            fin >> dist[i][j];
            if(i != j && dist[i][j] == 0) {
                dist[i][j] = 1e9;
            }
        }
    }
    for(int k = 1; k <= n; k++) {
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                if(dist[i][j] > dist[i][k] + dist[k][j]) {
                    dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }
    }
    //Roy Floyd : O(N^3)
    //Dijkstra: O(N * MlogN)

    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            if(dist[i][j] == 1e9) {
                fout << 0 << " ";
            } else {
                fout << dist[i][j] << " ";
            }
        }
        fout << "\n";
    }

    return 0;
}