Cod sursa(job #2312750)

Utilizator KaryamKaryam Ahmad Karyam Data 5 ianuarie 2019 14:31:10
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
/* Floyd-Warshall algorithm O(V^3)
   	- computes shortest path between all pairs of  2 nodes


*/

#include <bits/stdc++.h>
FILE *fin  = freopen("royfloyd.in", "r", stdin);
FILE *fout = freopen("royfloyd.out", "w", stdout);
using namespace std;
const int Vmax = 102;
const int oo = INT_MAX;

int nodes;
int dist[Vmax][Vmax];

void floyd_warshall() {
	for (int k = 0; k < nodes; ++ k) // iteratively add node k to the set of intermediate vertices
		for (int i = 0; i < nodes; ++ i) // iterate through source vertices
			for (int j = 0; j < nodes; ++ j) // iterate through destination vertices
				if (dist[i][k]!= oo && dist[k][j] != oo &&
						dist[i][j] > dist[i][k] + dist[k][j])
					dist[i][j] = dist[i][k] + dist[k][j];
}

int main() {
	scanf("%d", &nodes);
	for (int i = 0; i < nodes; ++i) // read the adjacency matrix
		for(int j = 0; j < nodes; ++j) {
			scanf("%d", &dist[i][j]);
			if(!dist[i][j] && i!=j) dist[i][j] = oo;
		}

	floyd_warshall();

	for (int i = 0; i < nodes; ++i) { // print the shortest path matrix
		for(int j = 0; j < nodes; ++j) {
			if(dist[i][j]==oo)
				printf("0 ");
			else printf("%d ", dist[i][j]);
		}
		printf("\n");
	}

	return 0;
}