Cod sursa(job #293570)

Utilizator Omega91Nicodei Eduard Omega91 Data 1 aprilie 2009 22:06:24
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

int const NMAX = 50001;

int CM[NMAX];

vector<int> graph[NMAX], cost[NMAX];

inline bool dhcomp(int a, int b)
{
	return CM[a] > CM[b];
}

void dijkstra(int start)
{
	int dh[NMAX] = {}; // Dijkstra heap
	int dhL; // dhLength
	int cn, i, neigh;
	dh[0] = start;
	dhL = 1;
	CM[start] = 0;
	while(dhL) {
		cn = dh[0]; // curent node
		std::pop_heap(dh, dh + dhL--, dhcomp);
		for (i = 0; i != graph[cn].size(); ++i) {
			neigh = graph[cn][i];
			if ( CM[neigh] == -1 ) { // if not processed
				CM[neigh] = CM[cn] + cost[cn][i];
				dh[dhL++] = neigh;
				std::push_heap(dh, dh + dhL, dhcomp);
			}
			else if (CM[cn] + cost[cn][i] < CM[neigh]) {
				CM[neigh] = CM[cn] + cost[cn][i];
				// note that here we traverse the whole heap
				// an optimization could be implemented in order to sort
				// only the branches CM[neigh] affects.
				std::make_heap(dh, dh + dhL, dhcomp);
			}
		}
	}
}

int main()
{
	int N, M, a, b, c, i;
	memset(CM, 0xFF, sizeof(int) * NMAX);
	freopen("dijkstra.out", "w", stdout);
	std::ifstream fin("dijkstra.in");
	fin >> N >> M;
	for (i = 0; i != M; ++i) {
		fin >> a >> b >> c;
		graph[a].push_back(b);
		cost [a].push_back(c);
	}
	dijkstra(1);
	for (i = 1; i <= N; ++i)
		if (CM[i] == -1) printf("0 ");
		else printf("%d ", CM[i]);
	printf("\n");
}