Cod sursa(job #2968738)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 21 ianuarie 2023 21:07:25
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
//
// Created by mihai145 on 21.01.2023.
//

#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream cin("royfloyd.in");
ofstream cout("royfloyd.out");

const int INF = 1000 * 100;
const bool SHOW_PATHS = false;

void show_path(int x, int y, vector<vector<int>> &d, vector<vector<int>> &p) {
    cout << "Drum minim de la " << x << " la " << y << " de lungime " << d[x][y] << ": ";

    if (d[x][y] == INF) {
        cout << "Nu sunt conectate!\n";
        return;
    }

    stack<int> stk;
    stk.push(y);
    while (p[x][y] != 0) {
        int z = p[x][y];
        stk.push(z);
        y = z;
    }

    while (!stk.empty()) {
        cout << stk.top() << ' ';
        stk.pop();
    }
    cout << '\n';
}

int main() {
    int n;
    cin >> n;

    vector<vector<int>> d(n + 1, vector<int>(n + 1, INF));
    vector<vector<int>> p(n + 1, vector<int>(n + 1, 0));

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> d[i][j];

            if (i == j) { continue; }

            if (d[i][j] == 0) {
                d[i][j] = INF;
            } else {
                p[i][j] = i;
            }
        }
    }

    for (int k = 1; k <= n; k++) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                int new_dist = d[i][k] + d[k][j];
                if (new_dist < d[i][j]) {
                    d[i][j] = new_dist;
                    p[i][j] = p[k][j];
                }
            }
        }
    }

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == j) {
                cout << 0 << ' ';
                continue;
            }

            if (d[i][j] == INF) {
                cout << 0 << ' ';
            } else {
                cout << d[i][j] << ' ';
            }
        }
        cout << '\n';
    }

    if (SHOW_PATHS) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                show_path(i, j, d, p);
            }
        }
    }

    return 0;
}