Cod sursa(job #1069084)

Utilizator dm1sevenDan Marius dm1seven Data 29 decembrie 2013 13:37:32
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <deque>
#include <limits>
using namespace std;

//int e_003_royfloyd()
int main()
{
	string in_file = "royfloyd.in";
	string out_file = "royfloyd.out";

	int N;
	const int MAX_N = 100;
	int weights[MAX_N + 1][MAX_N + 1];	
	//read the inputs
	ifstream ifs(in_file);
	ifs >> N;
	for (int v = 1; v <= N; v++) {
		for (int v2 = 1; v2 <= N; v2++) {
			ifs >> weights[v][v2];
		}
	}
	ifs.close();
	
	//processing
	int min_paths[MAX_N + 1][MAX_N + 1];
	char is_in_queue[MAX_N + 1];

	//for each vertex as source call Dijkstra
	for (int s = 1; s <= N; s++) {
		
		//init the state for Dijkstra
		for (int v = 1; v <= N; v++) {
			is_in_queue[v] = 0;
			min_paths[s][v] = std::numeric_limits<int>::max();
		}

		deque<int> Q;
		Q.push_back(s);
		min_paths[s][s] = 0;
		is_in_queue[s] = 1;

		while (!Q.empty()) {
			int v1 = Q.front();
			Q.pop_front();
			is_in_queue[v1] = 0;

			//parse the adiacency list
			for (int v2 = 1; v2 <= N; v2++) {
				if (weights[v1][v2] > 0) { //if the vertices have an edge
					int possible_cost = min_paths[s][v1] + weights[v1][v2];
					if (possible_cost < min_paths[s][v2]) {
						min_paths[s][v2] = possible_cost;
						if (!is_in_queue[v2]) {
							Q.push_back(v2);
							is_in_queue[v2] = 1;
						}
					}
				}
			}
		}

		for (int v2 = 1; v2 <= N; v2++) if (min_paths[s][v2] == std::numeric_limits<int>::max()) min_paths[s][v2] = 0;

	}
		
	ofstream ofs(out_file);
	for (int v1 = 1; v1 <= N; v1++) {
		for (int v2 = 1; v2 <= N; v2++)	ofs << min_paths[v1][v2] << " ";
		ofs << endl;
	}
	ofs.close();

	return 0;
}