Cod sursa(job #276883)

Utilizator stefysStefan stefys Data 11 martie 2009 13:08:24
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <fstream>
using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

const unsigned int MAXN = 50001;
const unsigned int INF = 0xEEEEEEEE;
unsigned int dist[MAXN],heappos[MAXN],heap[MAXN],heapsize=0;
char visited[MAXN];

inline unsigned int PARENT (unsigned int idx) { return (idx-1)>>1; }
inline unsigned int LEFT (unsigned int idx) { return (idx>>1)+1; }
inline unsigned int RIGHT (unsigned int idx) { return (idx>>1)+2; }
inline void SWAP (unsigned int &x, unsigned int &y) { unsigned int aux=x; x=y; y=aux; }

inline void heapify (unsigned int pos)
{
	while (LEFT(pos) < heapsize) {
		unsigned int min=dist[heap[pos]], minpos=pos;
		if (dist[heap[LEFT(pos)]] < min) { min = dist[heap[LEFT(pos)]]; minpos=LEFT(pos); }
		if (RIGHT(pos) < heapsize && dist[heap[RIGHT(pos)]]<min) { min=dist[heap[RIGHT(pos)]]; minpos=RIGHT(pos); }
		if (pos != minpos) {
			SWAP(heap[pos], heap[minpos]);
			heappos[heap[pos]] = pos;
			heappos[heap[minpos]] = minpos;
			pos=minpos;
		} else break;
	}
}

inline void heap_push (unsigned int idx)
{
	unsigned int pos;
	if (heappos[idx] == INF) pos=heapsize++;
	else pos = heappos[idx];
	while (pos > 0) {
		if (dist[idx] < dist[heap[PARENT(pos)]]) {
			heap[pos] = heap[PARENT(pos)];
			heappos[heap[pos]] = pos;
			pos = PARENT(pos);
		} else break;
	}
	heappos[idx] = pos;
	heap[pos] = idx;
}

inline unsigned int heap_pop ()
{
	unsigned int ret = heap[0];
	heap[0] = heap[--heapsize];
	heappos[ret] = INF;
	heappos[heap[0]] = 0;
	heapify(0);
	return ret;
}


struct Nod {
	unsigned int dest, cost;
	Nod *n;
};

Nod *graf[MAXN];

int main ()
{
	unsigned int N,M,i,src;
	in >> N >> M;
	for (i=0; i<M; ++i) {
		Nod *nod = new Nod;
		in >> src >> nod->dest >> nod->cost;
		nod->n = graf[src];
		graf[src] = nod;
	}
	
	for (i=1; i<=N; ++i) dist[i]=heappos[i]=INF;
	dist[1] = 0;
	memset(visited, 0, N+1);
	
	heap_push(1);
	while (heapsize > 0) {
		src = heap_pop();
		if (visited[src]) continue;
		visited[src] = 1;
		for (Nod *nod=graf[src]; nod; nod=nod->n) {
			if (dist[nod->dest] > dist[src]+nod->cost) {
				dist[nod->dest] = dist[src]+nod->cost;
				heap_push(nod->dest);
			}
		}
	}
	
	for (i=2; i<=N; ++i) out << (dist[i]==INF?0:dist[i]) << ' ';
	out << '\n';
	
	in.close();
	out.close();
	return 0;
}