Cod sursa(job #2611567)

Utilizator _mirubMiruna-Elena Banu _mirub Data 7 mai 2020 03:31:04
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
#define NMAX 109     
#define oo (1 << 20)
using namespace std;

class Task{
public:
  void solve() {
    read_input();
    get_result();
    print_output();
  }

private:  
    // Number of nodes
    int n;

    // p[i][j] = parend of j on the path i -> j
    int d[NMAX][NMAX], p[NMAX][NMAX];

    void read_input() {
        ifstream fin("royfloyd.in");
        fin >> n;
        for (int x = 1; x <= n; ++x) {
            for (int y = 1; y <= n; ++y) {
                int c; // x -> y, of cost c
                fin >> c;
                if (c == 0) {
                    c = oo;
                }
                d[x][y] = c;
                p[x][y] = x;
            }
        }
        fin.close();
    }

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

    void get_result() { RoyFloyd(); }

    // rebuild source -> ... -> node (if exists)
    void rebuild_path_recursive(int node, int source) {
        if (d[node][source] == oo) {
            cout << "Drum inexistent!";
            return;
        }

        if (node == source) {
            return;
        }

        // rebuild first source -> ...-> p[node]
        rebuild_path_recursive(p[node][source], source);
    }

    void print_output() {
        ofstream fout ("royfloyd.out");
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (d[i][j] == oo) {
                    d[i][j] = 0;
                }
                fout << d[i][j] << " ";
            }
            fout << "\n";
        }
        fout.close();
    }
};

int main() {
  Task *task = new Task();
  task->solve();
  delete task;
  return 0;
}