Cod sursa(job #2815258)

Utilizator Andreea__Zavoiu Andreea Andreea__ Data 9 decembrie 2021 12:56:35
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
// complexitatea O(n^3)
#include <iostream>
#include <fstream>
#define Nmax 101
#define valMax 1001
using namespace std;

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

int n, d[Nmax][Nmax];    //  d = matricea drumurilor minime

int main()
{
    fin >> n;
    for (int i=1; i<=n; i++)
        for (int j=1; j<=n; j++){
            fin >> d[i][j]; // citesc ponderea pentru fiecare muchie (i,j) si initializez matricea drumurilor minime cu ponderile
            if (d[i][j] == 0 && i!=j)
                d[i][j] = valMax;
        }

    // Vrem sa gasim drumul minim de la fiecare nod i la fiecare nod j (direct sau trecand prin noduri intermediare). Astfel:
    // pentru fiecare nod k de la 1 la n, verific pentru fiecare muchie (i,j) a matricei daca drumul trecand prin acel nod k (adica prin nodurile intermediare de la 1 la k)
    // nu cumva este mai mic decat drumul direct de la i la j sau drumul minim actualizat precedent, adica pentru nodurile intermediare de la 1 la k-1

    for(int k=1; k<=n; k++)
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                        d[i][j] = min (d[i][j], d[i][k] + d[k][j]); // actualizez drumul minim

    for (int i=1; i<=n; i++) {
        for (int j = 1; j <= n; j++)
            fout << d[i][j] << " ";
        fout << endl;
    }

    return 0;
}

/*
In the correct implementation, you need to find distance between two vertices 'n' times, since you have to consider shortest distance among
 all possible hops (and permutations of hops). So for each k (outermost iteration), you find the distance between a pair(i,j) considering 0
 to k nr of hops in between.
Lets take a different order: i,j,k. In this case, for the first outermost iteration(i=0), what you find is the shortest distance from a
 particular source(lets call it S, for i=0) considering shortest path to a destination either directly, or considering one hop in between.
!However, there can be shorter routes between source to hop or/and hop to destination which you may later find out in remaining iterations(i>0),
 but you will never be able to modify S again since i cannot be 0 in remaining iterations. !!!
*/