Cod sursa(job #3221541)

Utilizator george_buzasGeorge Buzas george_buzas Data 7 aprilie 2024 13:14:33
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#define MAX_DIMENSION 100
#define INF 1000000
using namespace std;
ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");

int mat[MAX_DIMENSION + 1][MAX_DIMENSION + 1];

void floydWarshall(int nrNodes) {
	for (int node = 1; node <= nrNodes; ++node) {
		for (int row = 1; row <= nrNodes; ++row) {
			if (row != node) {
				for (int col = 1; col <= nrNodes; ++col) {
					if (col != node) {
						mat[row][col] = min(mat[row][col], mat[row][node] + mat[node][col]);
					}
				}
			}
		}
	}
}

/*
* According to the problem description, if a path between two nodes is 0, then this means there is no path between them.
* In case there is still no path between 2 nodes even after applying the algorithm, then we mark their distance as being 0.
*/
void printAllPairsShortestDistances(int nrNodes) {
	for (int row = 1; row <= nrNodes; ++row) {
		for (int col = 1; col <= nrNodes; ++col) {
			if (mat[row][col] == INF) { 
				mat[row][col] = 0;
			}
			fout << mat[row][col] << ' ';
		}
		fout << '\n';
	}
}

int main() {
	int nrNodes;
	fin >> nrNodes;
	for (int row = 1; row <= nrNodes; ++row) {
		for (int col = 1; col <= nrNodes; ++col) {
			fin >> mat[row][col];
			if (row != col && mat[row][col] == 0) {
				mat[row][col] = INF; // mark this non-existent edge between two nodes(i.e. row and col)
			}
		}
	}
	floydWarshall(nrNodes);
	printAllPairsShortestDistances(nrNodes);
	return 0;
}