Cod sursa(job #2422473)

Utilizator nicu97oTuturuga Nicolae nicu97o Data 18 mai 2019 21:47:05
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
using namespace std;

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

void getAllShortestPaths(int** mat, int size);

int main() {
	int** dist;
	int nrOfVertices;
	fin >> nrOfVertices;
	dist = (int**)malloc(sizeof(int*) * nrOfVertices);
	for (int i = 0; i < nrOfVertices; ++i) {
		dist[i] = (int*)malloc(sizeof(int) * nrOfVertices);
		for (int j = 0; j < nrOfVertices; ++j) {
			fin >> dist[i][j];
		}
	}
	getAllShortestPaths(dist, nrOfVertices);
	for (int i = 0; i < nrOfVertices; ++i) {
		for (int j = 0; j < nrOfVertices; ++j) {
			fout << dist[i][j] << ' ';
		}
		fout << '\n';
		free(dist[i]);
	}
	free(dist);
	fin.close();
	fout.close();
	return 0;
}

void getAllShortestPaths(int** mat, int size) {
	for (int k = 0; k < size; ++k) {
		for (int i = 0; i < size; ++i) {
			for (int j = 0; j < size; ++j) {
				if (i != j && mat[i][k] != 0 && mat[k][j] != 0 && (mat[i][j] > mat[i][k] + mat[k][j] || mat[i][j] == 0)) {
					mat[i][j] = mat[i][k] + mat[k][j];
				}
			}
		}
	}
}